import 'package:flutter/material.dart';

import '../../../../core/services/student_performance_service.dart';

const Color _green = Color.fromARGB(255, 2, 105, 48);
const Color _gold = Color.fromARGB(255, 204, 117, 4);
const Color _ink = Color(0xFF1F3028);
const Color _muted = Color(0xFF68766F);
const Color _border = Color(0xFFE0E7E3);

class HodManagementSubTab extends StatefulWidget {
  final Future<void> Function()? onChanged;
  const HodManagementSubTab({super.key, this.onChanged});

  @override
  State<HodManagementSubTab> createState() => _HodManagementSubTabState();
}

class _HodManagementSubTabState extends State<HodManagementSubTab> {
  List<Map<String, dynamic>> _departments = const [];
  List<Map<String, dynamic>> _campuses = const [];
  List<Map<String, dynamic>> _staff = const [];
  List<HodAssignment> _assignments = const [];
  Map<String, dynamic>? _user;

  int? _departmentId;
  String _campus = '';
  int? _staffId;
  bool _loading = true;
  bool _saving = false;
  String? _error;
  String _search = '';

  bool get _isAdmin => StudentPerformanceService.roleIsAdmin('${_user?['role'] ?? ''}');

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    if (mounted) setState(() { _loading = true; _error = null; });
    try {
      final results = await Future.wait<dynamic>([
        StudentPerformanceService.getCurrentUser(),
        StudentPerformanceService.getDepartments(),
        StudentPerformanceService.getCampuses(),
        StudentPerformanceService.getStaff(),
        StudentPerformanceService.getHodAssignments(),
      ]);
      if (!mounted) return;
      setState(() {
        _user = Map<String, dynamic>.from(results[0] as Map);
        _departments = List<Map<String, dynamic>>.from(results[1] as List);
        _campuses = List<Map<String, dynamic>>.from(results[2] as List);
        _staff = List<Map<String, dynamic>>.from(results[3] as List);
        _assignments = List<HodAssignment>.from(results[4] as List);
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() { _loading = false; _error = e.toString().replaceFirst('Exception: ', ''); });
    }
  }

  Map<String, dynamic>? get _selectedDepartment {
    if (_departmentId == null) return null;
    for (final d in _departments) {
      if (_id(d) == _departmentId) return d;
    }
    return null;
  }

  List<Map<String, dynamic>> get _eligibleStaff {
    final department = _selectedDepartment;
    if (department == null || _campus.isEmpty) return const [];
    final departmentName = _name(department).toLowerCase();
    final list = _staff.where((s) {
      final role = '${s['role'] ?? ''}'.toLowerCase().trim();
      final campus = '${s['campus'] ?? ''}'.trim().toLowerCase();
      final program = '${s['program'] ?? s['department'] ?? ''}'.trim().toLowerCase();
      return role == 'staff' && campus == _campus.toLowerCase() && program == departmentName;
    }).toList();
    list.sort((a, b) => _staffName(a).toLowerCase().compareTo(_staffName(b).toLowerCase()));
    return list;
  }

  Future<void> _assign() async {
    if (_saving) return;
    if (_departmentId == null || _campus.isEmpty || _staffId == null) {
      _snack('Select a campus, department and eligible staff member.', error: true);
      return;
    }
    setState(() => _saving = true);
    try {
      await StudentPerformanceService.assignHod(
        departmentId: _departmentId!,
        campus: _campus,
        staffUserId: _staffId!,
      );
      _snack('HOD assignment saved successfully.');
      setState(() => _staffId = null);
      await _load();
      if (widget.onChanged != null) await widget.onChanged!();
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  Future<void> _end(HodAssignment assignment) async {
    final yes = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        title: const Text('End HOD assignment?'),
        content: Text('${assignment.staffName} will no longer be able to submit promotion examination results for ${assignment.departmentName} at ${assignment.campus}.'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          FilledButton(onPressed: () => Navigator.pop(context, true), style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700), child: const Text('End Assignment')),
        ],
      ),
    );
    if (yes != true) return;
    try {
      await StudentPerformanceService.endHodAssignment(assignment.id);
      await _load();
      if (widget.onChanged != null) await widget.onChanged!();
      _snack('HOD assignment ended.');
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    }
  }

  void _snack(String message, {bool error = false}) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(message), backgroundColor: error ? Colors.red.shade700 : _green,
      behavior: SnackBarBehavior.floating,
    ));
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) return const Center(child: CircularProgressIndicator(color: _green));
    if (_error != null) return _centerMessage(Icons.cloud_off_rounded, 'Unable to load HOD management', _error!, action: _load);
    if (!_isAdmin) return _centerMessage(Icons.admin_panel_settings_rounded, 'Administrator Access Required', 'Only administrators can assign or remove Heads of Department.');

    return LayoutBuilder(builder: (context, constraints) {
      final compact = constraints.maxWidth < 820;
      return RefreshIndicator(
        onRefresh: _load,
        color: _green,
        child: ListView(
          padding: EdgeInsets.fromLTRB(compact ? 12 : 24, 18, compact ? 12 : 24, 80),
          children: [
            Text('Head of Department Management', style: TextStyle(fontSize: compact ? 19 : 23, fontWeight: FontWeight.w900, color: _ink)),
            const SizedBox(height: 5),
            const Text('Administrators assign one active HOD per campus and department. Departments are loaded directly from the departments database.', style: TextStyle(color: _muted, fontSize: 12.5, height: 1.4)),
            const SizedBox(height: 16),
            _assignmentComposer(compact),
            const SizedBox(height: 22),
            Row(children: [
              const Expanded(child: Text('Current HOD Assignments', style: TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 16))),
              SizedBox(width: compact ? 150 : 240, child: TextField(
                onChanged: (value) => setState(() => _search = value.trim().toLowerCase()),
                decoration: _decor('Search', Icons.search_rounded),
              )),
            ]),
            const SizedBox(height: 10),
            if (_filteredAssignments.isEmpty)
              _centerMessage(Icons.person_search_rounded, 'No HOD assignments', 'Assign an eligible staff member to a department to begin.')
            else
              ..._groupedAssignments(compact),
          ],
        ),
      );
    });
  }

  Widget _assignmentComposer(bool compact) {
    final campusNames = _campuses.map(_name).where((e) => e.isNotEmpty).toSet().toList()..sort();
    final departments = [..._departments]..sort((a, b) => _name(a).compareTo(_name(b)));
    final eligible = _eligibleStaff;
    final campusField = DropdownButtonFormField<String>(
      value: _campus.isEmpty ? null : _campus,
      isExpanded: true,
      decoration: _decor('Campus', Icons.apartment_rounded),
      items: campusNames.map((value) => DropdownMenuItem(value: value, child: Text(value))).toList(),
      onChanged: (value) => setState(() { _campus = value ?? ''; _staffId = null; }),
    );
    final departmentField = DropdownButtonFormField<int>(
      value: _departmentId,
      isExpanded: true,
      decoration: _decor('Department', Icons.account_tree_rounded),
      items: departments.where((d) => _id(d) > 0).map((d) => DropdownMenuItem(value: _id(d), child: Text(_name(d), overflow: TextOverflow.ellipsis))).toList(),
      onChanged: (value) => setState(() { _departmentId = value; _staffId = null; }),
    );
    final staffField = DropdownButtonFormField<int>(
      value: eligible.any((s) => _id(s) == _staffId) ? _staffId : null,
      isExpanded: true,
      decoration: _decor('Eligible staff member', Icons.person_rounded),
      items: eligible.map((s) => DropdownMenuItem(value: _id(s), child: Text(_staffName(s), overflow: TextOverflow.ellipsis))).toList(),
      onChanged: eligible.isEmpty ? null : (value) => setState(() => _staffId = value),
    );

    return Container(
      padding: EdgeInsets.all(compact ? 15 : 20),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(18), border: Border.all(color: _border)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(children: [
          Container(width: 42, height: 42, decoration: BoxDecoration(color: _green.withOpacity(.08), borderRadius: BorderRadius.circular(12)), child: const Icon(Icons.person_add_alt_1_rounded, color: _green)),
          const SizedBox(width: 10),
          const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Assign a Head of Department', style: TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 15)), SizedBox(height: 2), Text('A new assignment automatically closes the previous active HOD for that campus and department.', style: TextStyle(color: _muted, fontSize: 10.5))])),
        ]),
        const SizedBox(height: 16),
        if (compact) ...[
          campusField, const SizedBox(height: 10), departmentField, const SizedBox(height: 10), staffField,
        ] else
          Row(children: [Expanded(child: campusField), const SizedBox(width: 10), Expanded(child: departmentField), const SizedBox(width: 10), Expanded(child: staffField)]),
        if (_campus.isNotEmpty && _departmentId != null && eligible.isEmpty) ...[
          const SizedBox(height: 10),
          Container(width: double.infinity, padding: const EdgeInsets.all(11), decoration: BoxDecoration(color: _gold.withOpacity(.08), borderRadius: BorderRadius.circular(10)), child: const Text('No staff member currently belongs to both the selected campus and department. Update the staff profile first, then assign the HOD.', style: TextStyle(color: Color(0xFF7A4B00), fontSize: 10.8, height: 1.4))),
        ],
        const SizedBox(height: 14),
        Align(alignment: Alignment.centerRight, child: FilledButton.icon(
          onPressed: _saving ? null : _assign,
          icon: _saving ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.verified_user_rounded),
          label: Text(_saving ? 'Assigning...' : 'Assign HOD'),
          style: FilledButton.styleFrom(backgroundColor: _green, padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
        )),
      ]),
    );
  }

  List<HodAssignment> get _filteredAssignments {
    if (_search.isEmpty) return _assignments;
    return _assignments.where((a) => '${a.staffName} ${a.departmentName} ${a.campus} ${a.school}'.toLowerCase().contains(_search)).toList();
  }

  List<Widget> _groupedAssignments(bool compact) {
    final groups = <String, List<HodAssignment>>{};
    for (final a in _filteredAssignments) groups.putIfAbsent(a.campus, () => []).add(a);
    final keys = groups.keys.toList()..sort();
    return keys.map((campus) => Container(
      margin: const EdgeInsets.only(bottom: 15),
      decoration: BoxDecoration(color: Colors.white, border: Border.all(color: _border), borderRadius: BorderRadius.circular(16)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Padding(padding: const EdgeInsets.all(15), child: Row(children: [const Icon(Icons.apartment_rounded, color: _green), const SizedBox(width: 8), Expanded(child: Text(campus, style: const TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 14.5))), Text('${groups[campus]!.length} department${groups[campus]!.length == 1 ? '' : 's'}', style: const TextStyle(color: _muted, fontSize: 10.5))])),
        const Divider(height: 1, color: _border),
        ...groups[campus]!.map((a) => _assignmentRow(a, compact)),
      ]),
    )).toList();
  }

  Widget _assignmentRow(HodAssignment a, bool compact) {
    final info = Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text(a.departmentName, style: const TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 12.5)),
      const SizedBox(height: 3),
      Text(a.staffName.isEmpty ? 'Staff #${a.staffUserId}' : a.staffName, style: const TextStyle(fontWeight: FontWeight.w700, color: _green, fontSize: 11.5)),
      if (a.school.isNotEmpty) ...[const SizedBox(height: 2), Text(a.school, style: const TextStyle(color: _muted, fontSize: 10.5))],
    ]);
    final button = OutlinedButton.icon(onPressed: () => _end(a), icon: const Icon(Icons.person_remove_outlined, size: 17), label: const Text('End'), style: OutlinedButton.styleFrom(foregroundColor: Colors.red.shade700));
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 13),
      decoration: const BoxDecoration(border: Border(bottom: BorderSide(color: Color(0xFFEEF1EF)))),
      child: compact ? Column(crossAxisAlignment: CrossAxisAlignment.start, children: [info, const SizedBox(height: 9), button]) : Row(children: [Expanded(child: info), if (a.staffEmail.isNotEmpty) Expanded(child: Text(a.staffEmail, style: const TextStyle(color: _muted, fontSize: 10.5))), button]),
    );
  }

  Widget _centerMessage(IconData icon, String title, String message, {VoidCallback? action}) => Center(child: Container(
    constraints: const BoxConstraints(maxWidth: 620),
    margin: const EdgeInsets.all(20), padding: const EdgeInsets.all(30),
    decoration: BoxDecoration(color: Colors.white, border: Border.all(color: _border), borderRadius: BorderRadius.circular(18)),
    child: Column(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 50, color: Colors.grey.shade300), const SizedBox(height: 12), Text(title, textAlign: TextAlign.center, style: const TextStyle(fontSize: 17, fontWeight: FontWeight.w900, color: _ink)), const SizedBox(height: 7), Text(message, textAlign: TextAlign.center, style: const TextStyle(color: _muted, height: 1.45)), if (action != null) ...[const SizedBox(height: 14), FilledButton.icon(onPressed: action, icon: const Icon(Icons.refresh), label: const Text('Try again'), style: FilledButton.styleFrom(backgroundColor: _green))]]),
  ));

  InputDecoration _decor(String label, IconData icon) => InputDecoration(labelText: label, prefixIcon: Icon(icon, color: _green, size: 19), filled: true, fillColor: const Color(0xFFF9FBFA), border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _border)), enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _border)), focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _green, width: 1.3)));

  String _name(Map<String, dynamic> row) => '${row['name'] ?? row['title'] ?? ''}'.trim();
  int _id(Map<String, dynamic> row) => int.tryParse('${row['id'] ?? 0}') ?? 0;
  String _staffName(Map<String, dynamic> row) => '${row['full_name'] ?? row['name'] ?? 'Unnamed Staff'}'.trim();
}

class AdminHodManagementTab extends StatelessWidget {
  const AdminHodManagementTab({super.key});

  @override
  Widget build(BuildContext context) => const Scaffold(
    backgroundColor: Color(0xFFF3F6F5),
    body: HodManagementSubTab(),
  );
}
