// lib/features/admin/tabs/positions/school/school_directory_sub_tab.dart

import 'package:flutter/material.dart';
import '../../../../../core/networks/api_client.dart';
import 'add_school_sub_tab.dart';

const _standardGold = Color.fromARGB(255, 204, 117, 4);
const _darkGreen = Color.fromARGB(255, 2, 105, 48);

class SchoolDirectorySubTab extends StatefulWidget {
  const SchoolDirectorySubTab({super.key});

  @override
  State<SchoolDirectorySubTab> createState() => _SchoolDirectorySubTabState();
}

class _SchoolDirectorySubTabState extends State<SchoolDirectorySubTab> {
  final _horizontal = ScrollController();
  final _vertical = ScrollController();

  List<Map<String, dynamic>> _schools = [];
  bool _loading = false;
  bool _dialogOpen = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    ApiClient.dataChanges.addListener(_onSchoolsDataChange);
    _loadSchools();
  }

  void _onSchoolsDataChange() {
    final change = ApiClient.dataChanges.value;
    final endpoint = Uri.parse('${ApiClient.baseUrl}/api/schools.php');
    if (change == null || change.isMutation ||
        !ApiClient.sameApiFamily(change.url, endpoint)) return;
    Future<void>.delayed(const Duration(milliseconds: 100), () {
      if (mounted) _loadSchools(refresh: false, showLoading: false);
    });
  }

  Future<void> _loadSchools({bool refresh = false, bool showLoading = true}) async {
    if (!mounted || (_loading && showLoading)) return;

    if (showLoading) {
      setState(() {
        _loading = true;
        _error = null;
      });
    }

    try {
      final data = await ApiClient.getSchools(refresh: refresh);
      final schools = <Map<String, dynamic>>[];

      for (final row in data) {
        if (row is! Map) {
          throw const FormatException('Invalid school record.');
        }
        schools.add(
          row.map((key, value) => MapEntry(key.toString(), value)),
        );
      }

      if (mounted) {
        setState(() => _schools = schools);
      }
    } catch (error) {
      if (mounted) {
        setState(() => _error = error.toString());
      }
    } finally {
      if (mounted && showLoading) {
        setState(() => _loading = false);
      }
    }
  }

  void _notice(String text) {
    ScaffoldMessenger.maybeOf(context)?.showSnackBar(
      SnackBar(content: Text(text), backgroundColor: _darkGreen),
    );
  }

  Future<void> _openSchool([Map<String, dynamic>? school]) async {
    if (_dialogOpen || _loading) return;

    setState(() => _dialogOpen = true);
    try {
      final saved = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (_) => AddSchoolDialog(schoolToEdit: school),
      );

      if (!mounted) return;

      if (saved == true) {
        _notice(
          school == null
              ? 'School added successfully.'
              : 'School updated successfully.',
        );
        await _loadSchools(refresh: true);
      }
    } finally {
      if (mounted) {
        setState(() => _dialogOpen = false);
      }
    }
  }

  Future<void> _delete(Map<String, dynamic> school) async {
    if (_dialogOpen || _loading) return;

    setState(() => _dialogOpen = true);
    try {
      final deleted = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (_) => _DeleteSchoolDialog(school: school),
      );

      if (!mounted) return;

      if (deleted == true) {
        _notice('School removed successfully.');
        await _loadSchools(refresh: true);
      }
    } finally {
      if (mounted) {
        setState(() => _dialogOpen = false);
      }
    }
  }

  @override
  void dispose() {
    ApiClient.dataChanges.removeListener(_onSchoolsDataChange);
    _horizontal.dispose();
    _vertical.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Material(
        color: const Color(0xFFF7F8FA),
        child: LayoutBuilder(
          builder: (context, bounds) {
            final size = MediaQuery.of(context).size;
            final width = bounds.hasBoundedWidth ? bounds.maxWidth : size.width;
            final height = bounds.hasBoundedHeight
                ? bounds.maxHeight
                : size.height * 0.8;

            return SizedBox(
              width: width,
              height: height,
              child: Padding(
                padding: EdgeInsets.all(width < 650 ? 12 : 24),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Wrap(
                      alignment: WrapAlignment.spaceBetween,
                      spacing: 16,
                      runSpacing: 12,
                      crossAxisAlignment: WrapCrossAlignment.center,
                      children: [
                        const Text(
                          'SCHOOL DIRECTORY',
                          style: TextStyle(
                            color: Color(0xFF24332B),
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                        Wrap(
                          spacing: 8,
                          runSpacing: 8,
                          children: [
                            IconButton(
                              tooltip: 'Refresh schools',
                              onPressed: _loading || _dialogOpen
                                  ? null
                                  : _loadSchools,
                              icon: const Icon(Icons.refresh, color: _darkGreen),
                            ),
                            ElevatedButton.icon(
                              onPressed: _dialogOpen || _loading
                                  ? null
                                  : () => _openSchool(),
                              icon: const Icon(Icons.add),
                              label: const Text('ADD SCHOOL'),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: _standardGold,
                                foregroundColor: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: const Color(0xFFDCE3DE)),
                        ),
                        child: _loading
                            ? const Center(
                                child: CircularProgressIndicator(
                                  color: _darkGreen,
                                ),
                              )
                            : _error != null
                                ? SingleChildScrollView(
                                    padding: const EdgeInsets.all(24),
                                    child: Column(
                                      children: [
                                        const Text(
                                          'Unable to load schools',
                                          style: TextStyle(
                                            color: Color(0xFF24332B),
                                            fontWeight: FontWeight.w700,
                                          ),
                                        ),
                                        const SizedBox(height: 12),
                                        SelectableText(
                                          _error!,
                                          style: const TextStyle(
                                            color: Colors.redAccent,
                                          ),
                                        ),
                                        const SizedBox(height: 12),
                                        OutlinedButton(
                                          onPressed: _loadSchools,
                                          child: const Text('Try again'),
                                        ),
                                      ],
                                    ),
                                  )
                                : _schools.isEmpty
                                    ? const Center(
                                        child: Text(
                                          'No schools registered yet.',
                                          style: TextStyle(
                                            color: Color(0xFF68776E),
                                          ),
                                        ),
                                      )
                                    : LayoutBuilder(
                                        builder: (context, table) =>
                                            SingleChildScrollView(
                                          controller: _vertical,
                                          child: SingleChildScrollView(
                                            controller: _horizontal,
                                            scrollDirection: Axis.horizontal,
                                            child: ConstrainedBox(
                                              constraints: BoxConstraints(
                                                minWidth: table.maxWidth,
                                              ),
                                              child: DataTable(
                                                headingRowColor:
                                                    WidgetStateProperty.all(
                                                  _darkGreen,
                                                ),
                                                headingTextStyle:
                                                    const TextStyle(
                                                  color: Colors.white,
                                                  fontWeight: FontWeight.w700,
                                                ),
                                                dataTextStyle: const TextStyle(
                                                  color: Color(0xFF24332B),
                                                ),
                                                dataRowMinHeight: 60,
                                                dataRowMaxHeight: 72,
                                                columns: const [
                                                  DataColumn(
                                                    label: Text('SCHOOL NAME'),
                                                  ),
                                                  DataColumn(
                                                    label: Text('DESCRIPTION'),
                                                  ),
                                                  DataColumn(
                                                    label: Text('ACTIONS'),
                                                  ),
                                                ],
                                                rows: _schools
                                                    .map(
                                                      (school) => DataRow(
                                                        cells: [
                                                          DataCell(
                                                            Text(
                                                              school['name']
                                                                      ?.toString() ??
                                                                  'Unnamed school',
                                                            ),
                                                          ),
                                                          DataCell(
                                                            SizedBox(
                                                              width: 360,
                                                              child: Text(
                                                                school['description']
                                                                        ?.toString() ??
                                                                    'No description provided',
                                                                maxLines: 2,
                                                                overflow:
                                                                    TextOverflow
                                                                        .ellipsis,
                                                              ),
                                                            ),
                                                          ),
                                                          DataCell(
                                                            Row(
                                                              mainAxisSize:
                                                                  MainAxisSize
                                                                      .min,
                                                              children: [
                                                                IconButton(
                                                                  tooltip:
                                                                      'Edit school',
                                                                  onPressed:
                                                                      _dialogOpen
                                                                          ? null
                                                                          : () =>
                                                                              _openSchool(school),
                                                                  icon:
                                                                      const Icon(
                                                                    Icons
                                                                        .edit_outlined,
                                                                    size: 20,
                                                                    color:
                                                                        _darkGreen,
                                                                  ),
                                                                ),
                                                                IconButton(
                                                                  tooltip:
                                                                      'Delete school',
                                                                  onPressed:
                                                                      _dialogOpen
                                                                          ? null
                                                                          : () =>
                                                                              _delete(school),
                                                                  icon:
                                                                      const Icon(
                                                                    Icons
                                                                        .delete_outline,
                                                                    size: 20,
                                                                    color: Colors
                                                                        .redAccent,
                                                                  ),
                                                                ),
                                                              ],
                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                    )
                                                    .toList(),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      );
}

class _DeleteSchoolDialog extends StatefulWidget {
  final Map<String, dynamic> school;

  const _DeleteSchoolDialog({required this.school});

  @override
  State<_DeleteSchoolDialog> createState() => _DeleteSchoolDialogState();
}

class _DeleteSchoolDialogState extends State<_DeleteSchoolDialog> {
  bool _busy = false;
  String? _error;

  Future<void> _delete() async {
    if (_busy) return;

    setState(() {
      _busy = true;
      _error = null;
    });

    try {
      final id = int.tryParse(widget.school['id']?.toString() ?? '');
      if (id == null || id <= 0) {
        throw Exception('Invalid school ID. Reload the directory.');
      }

      await ApiClient.deleteSchool(id);

      if (mounted) {
        Navigator.of(context).pop(true);
      }
    } catch (error) {
      if (mounted) {
        setState(() => _error = error.toString());
      }
    } finally {
      if (mounted) {
        setState(() => _busy = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) => PopScope(
        canPop: !_busy,
        child: AlertDialog(
          backgroundColor: Colors.white,
          title: const Text(
            'Remove school',
            style: TextStyle(color: Color(0xFF24332B)),
          ),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Remove ${widget.school['name'] ?? 'this school'}? This action cannot be undone.',
                  style: const TextStyle(color: Color(0xFF24332B)),
                ),
                if (_error != null) ...[
                  const SizedBox(height: 12),
                  SelectableText(
                    _error!,
                    style: const TextStyle(color: Colors.redAccent),
                  ),
                ],
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: _busy ? null : () => Navigator.of(context).pop(false),
              child: const Text('CANCEL'),
            ),
            ElevatedButton(
              onPressed: _busy ? null : _delete,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.redAccent,
                foregroundColor: Colors.white,
              ),
              child: Text(_busy ? 'DELETING...' : 'DELETE'),
            ),
          ],
        ),
      );
}
