// lib/features/admin/tabs/positions/department/department_directory_sub_tab.dart

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

const _standardGold = Color.fromARGB(255, 204, 117, 4);
const _darkGreen = Color.fromARGB(255, 2, 105, 48);
const _ink = Color(0xFF24332B);
const _muted = Color(0xFF68776E);
const _border = Color(0xFFDDE5E0);
const _surface = Color(0xFFF5F7F6);

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

  @override
  State<DepartmentDirectorySubTab> createState() =>
      _DepartmentDirectorySubTabState();
}

class _DepartmentDirectorySubTabState
    extends State<DepartmentDirectorySubTab> {
  final _vertical = ScrollController();
  final _searchController = TextEditingController();

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

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

  @override
  void dispose() {
    _vertical.dispose();
    _searchController.dispose();
    super.dispose();
  }

  String _text(dynamic value, [String fallback = '']) {
    final text = value?.toString().trim() ?? '';
    if (text.isEmpty || text.toLowerCase() == 'null') return fallback;
    return text;
  }

  int _int(dynamic value) => int.tryParse('${value ?? ''}') ?? 0;

  bool _truthy(dynamic value) =>
      value == true || value == 1 || value == '1' || value == 't' || value == 'true';

  List<Map<String, dynamic>> _hodAssignments(Map<String, dynamic> department) {
    final raw = department['hod_assignments'];
    if (raw is! List) return const <Map<String, dynamic>>[];
    final rows = raw
        .whereType<Map>()
        .map((row) => row.map((key, value) => MapEntry(key.toString(), value)))
        .toList();
    rows.sort((a, b) => _text(a['campus'])
        .toLowerCase()
        .compareTo(_text(b['campus']).toLowerCase()));
    return rows;
  }

  List<Map<String, dynamic>> get _filteredDepartments {
    final query = _search.trim().toLowerCase();
    if (query.isEmpty) return _departments;
    return _departments.where((department) {
      final hodText = _hodAssignments(department)
          .map((assignment) =>
              '${_text(assignment['campus'])} ${_text(assignment['hod_name'])} ${_text(assignment['hod_email'])}')
          .join(' ');
      final haystack = [
        _text(department['name']),
        _text(department['description']),
        hodText,
      ].join(' ').toLowerCase();
      return haystack.contains(query);
    }).toList();
  }

  int get _fullyCoveredCount =>
      _departments.where((department) => _truthy(department['hod_complete'])).length;

  int get _campusCount {
    int maxCount = 0;
    for (final department in _departments) {
      final value = _int(department['campus_count']);
      if (value > maxCount) maxCount = value;
    }
    return maxCount;
  }

  Future<void> _loadDepartments() async {
    if (!mounted || _loading) return;

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

    try {
      final data = await ApiClient.getDepartments();
      final departments = <Map<String, dynamic>>[];

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

      departments.sort((a, b) => _text(a['name'])
          .toLowerCase()
          .compareTo(_text(b['name']).toLowerCase()));

      if (mounted) setState(() => _departments = departments);
    } catch (error) {
      if (mounted) {
        setState(() => _error = error.toString().replaceFirst('Exception: ', ''));
      }
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  void _notice(String text, {bool error = false}) {
    ScaffoldMessenger.maybeOf(context)?.showSnackBar(
      SnackBar(
        content: Text(text),
        backgroundColor: error ? Colors.red.shade700 : _darkGreen,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  Future<void> _openDepartment([Map<String, dynamic>? department]) async {
    if (_dialogOpen || _loading) return;
    setState(() => _dialogOpen = true);

    try {
      final saved = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (_) => AddDepartmentDialog(departmentToEdit: department),
      );

      if (!mounted) return;
      if (saved == true) {
        _notice(
          department == null
              ? 'Department and campus HOD assignments created successfully.'
              : 'Department and campus HOD assignments updated successfully.',
        );
        await _loadDepartments();
      }
    } finally {
      if (mounted) setState(() => _dialogOpen = false);
    }
  }

  Future<void> _delete(Map<String, dynamic> department) async {
    if (_dialogOpen || _loading) return;
    setState(() => _dialogOpen = true);

    try {
      final deleted = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (_) => _DeleteDepartmentDialog(department: department),
      );

      if (!mounted) return;
      if (deleted == true) {
        _notice('Department removed successfully.');
        await _loadDepartments();
      }
    } finally {
      if (mounted) setState(() => _dialogOpen = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: _surface,
      child: LayoutBuilder(
        builder: (context, bounds) {
          final width = bounds.maxWidth;
          final compact = width < 640;
          final medium = width < 980;
          final padding = compact ? 12.0 : (medium ? 18.0 : 24.0);

          return Padding(
            padding: EdgeInsets.all(padding),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                _buildTopBar(compact),
                const SizedBox(height: 14),
                _buildSummary(compact),
                const SizedBox(height: 14),
                _buildSearchAndActions(compact),
                const SizedBox(height: 14),
                Expanded(child: _buildContent()),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildTopBar(bool compact) {
    return Container(
      padding: EdgeInsets.all(compact ? 15 : 20),
      decoration: BoxDecoration(
        color: _darkGreen,
        borderRadius: BorderRadius.circular(compact ? 16 : 20),
        border: const Border(bottom: BorderSide(color: _standardGold, width: 3)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(.08),
            blurRadius: 16,
            offset: const Offset(0, 7),
          ),
        ],
      ),
      child: Row(
        children: [
          Container(
            width: compact ? 42 : 50,
            height: compact ? 42 : 50,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(.12),
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: Colors.white.withOpacity(.18)),
            ),
            child: const Icon(Icons.account_tree_rounded, color: Colors.white),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'DEPARTMENT DIRECTORY',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: compact ? 16 : 20,
                    fontWeight: FontWeight.w900,
                    letterSpacing: .8,
                  ),
                ),
                const SizedBox(height: 3),
                Text(
                  'One university-wide department record with a different HOD for each campus.',
                  maxLines: compact ? 2 : 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white.withOpacity(.78),
                    fontSize: compact ? 10.5 : 12,
                    height: 1.35,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSummary(bool compact) {
    final items = <_MetricData>[
      _MetricData(
        icon: Icons.account_tree_outlined,
        value: '${_departments.length}',
        label: 'Departments',
      ),
      _MetricData(
        icon: Icons.location_city_outlined,
        value: '$_campusCount',
        label: 'Campuses',
      ),
      _MetricData(
        icon: Icons.verified_user_outlined,
        value: '$_fullyCoveredCount/${_departments.length}',
        label: 'Complete HOD coverage',
      ),
    ];

    if (compact) {
      return SizedBox(
        height: 88,
        child: ListView.separated(
          scrollDirection: Axis.horizontal,
          itemCount: items.length,
          separatorBuilder: (_, __) => const SizedBox(width: 9),
          itemBuilder: (_, index) => SizedBox(
            width: 172,
            child: _MetricCard(data: items[index]),
          ),
        ),
      );
    }

    return Row(
      children: items
          .map((item) => Expanded(
                child: Padding(
                  padding: EdgeInsets.only(right: item == items.last ? 0 : 10),
                  child: _MetricCard(data: item),
                ),
              ))
          .toList(),
    );
  }

  Widget _buildSearchAndActions(bool compact) {
    final search = TextField(
      controller: _searchController,
      onChanged: (value) => setState(() => _search = value),
      decoration: InputDecoration(
        hintText: 'Search department, campus or HOD...',
        prefixIcon: const Icon(Icons.search_rounded, color: _muted),
        suffixIcon: _search.isNotEmpty
            ? IconButton(
                tooltip: 'Clear search',
                icon: const Icon(Icons.close_rounded, size: 19),
                onPressed: () {
                  _searchController.clear();
                  setState(() => _search = '');
                },
              )
            : null,
        filled: true,
        fillColor: Colors.white,
        contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(13),
          borderSide: const BorderSide(color: _border),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(13),
          borderSide: const BorderSide(color: _border),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(13),
          borderSide: const BorderSide(color: _darkGreen, width: 1.5),
        ),
      ),
    );

    final refresh = OutlinedButton.icon(
      onPressed: _loading || _dialogOpen ? null : _loadDepartments,
      icon: const Icon(Icons.refresh_rounded),
      label: const Text('REFRESH'),
      style: OutlinedButton.styleFrom(
        foregroundColor: _darkGreen,
        side: const BorderSide(color: _border),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 15),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      ),
    );

    final add = ElevatedButton.icon(
      onPressed: _dialogOpen || _loading ? null : () => _openDepartment(),
      icon: const Icon(Icons.add_rounded),
      label: const Text('ADD DEPARTMENT'),
      style: ElevatedButton.styleFrom(
        backgroundColor: _standardGold,
        foregroundColor: Colors.white,
        elevation: 0,
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 15),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      ),
    );

    if (compact) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          search,
          const SizedBox(height: 10),
          Row(
            children: [
              Expanded(child: refresh),
              const SizedBox(width: 9),
              Expanded(flex: 2, child: add),
            ],
          ),
        ],
      );
    }

    return Row(
      children: [
        Expanded(child: search),
        const SizedBox(width: 10),
        refresh,
        const SizedBox(width: 10),
        add,
      ],
    );
  }

  Widget _buildContent() {
    if (_loading && _departments.isEmpty) {
      return const Center(child: CircularProgressIndicator(color: _darkGreen));
    }

    if (_error != null && _departments.isEmpty) {
      return _DirectoryError(message: _error!, onRetry: _loadDepartments);
    }

    if (_departments.isEmpty) {
      return _EmptyDirectory(onAdd: () => _openDepartment());
    }

    final rows = _filteredDepartments;
    if (rows.isEmpty) {
      return const Center(
        child: Text(
          'No department matches your search.',
          style: TextStyle(color: _muted, fontWeight: FontWeight.w700),
        ),
      );
    }

    return LayoutBuilder(
      builder: (context, constraints) {
        final width = constraints.maxWidth;
        final columns = width >= 1320 ? 3 : (width >= 780 ? 2 : 1);
        const spacing = 14.0;
        final cardWidth = columns == 1
            ? width
            : (width - (spacing * (columns - 1))) / columns;

        return Scrollbar(
          controller: _vertical,
          thumbVisibility: width >= 780,
          child: SingleChildScrollView(
            controller: _vertical,
            padding: const EdgeInsets.only(bottom: 24),
            child: Wrap(
              spacing: spacing,
              runSpacing: spacing,
              children: rows
                  .map((department) => SizedBox(
                        width: cardWidth,
                        child: _departmentCard(department),
                      ))
                  .toList(),
            ),
          ),
        );
      },
    );
  }

  Widget _departmentCard(Map<String, dynamic> department) {
    final name = _text(department['name'], 'Unnamed department');
    final description = _text(
      department['description'],
      'No department description has been provided.',
    );
    final assignments = _hodAssignments(department);
    final assigned = _int(department['hod_assigned_count']);
    final campuses = _int(department['campus_count']);
    final complete = _truthy(department['hod_complete']);

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        border: Border.all(color: complete ? _darkGreen.withOpacity(.18) : _border),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(.035),
            blurRadius: 14,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      clipBehavior: Clip.antiAlias,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: complete ? const Color(0xFFF1F8F3) : const Color(0xFFFFF8EE),
              border: const Border(bottom: BorderSide(color: _border)),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 42,
                  height: 42,
                  decoration: BoxDecoration(
                    color: _darkGreen.withOpacity(.09),
                    borderRadius: BorderRadius.circular(13),
                  ),
                  child: const Icon(Icons.account_tree_rounded, color: _darkGreen),
                ),
                const SizedBox(width: 11),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        name,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                          color: _ink,
                          fontSize: 15,
                          fontWeight: FontWeight.w900,
                          height: 1.2,
                        ),
                      ),
                      const SizedBox(height: 5),
                      _CoverageBadge(
                        complete: complete,
                        assigned: assigned,
                        campuses: campuses,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 14, 16, 10),
            child: Text(
              description,
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(color: _muted, fontSize: 11.5, height: 1.45),
            ),
          ),
          const Padding(
            padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
            child: Row(
              children: [
                Icon(Icons.supervisor_account_rounded, color: _darkGreen, size: 18),
                SizedBox(width: 7),
                Text(
                  'CAMPUS HODs',
                  style: TextStyle(
                    color: _ink,
                    fontSize: 10.5,
                    fontWeight: FontWeight.w900,
                    letterSpacing: .6,
                  ),
                ),
              ],
            ),
          ),
          if (assignments.isEmpty)
            const Padding(
              padding: EdgeInsets.fromLTRB(16, 2, 16, 16),
              child: Text(
                'No campus HOD assignments yet. Edit this department to complete the leadership setup.',
                style: TextStyle(color: Colors.redAccent, fontSize: 10.8, height: 1.4),
              ),
            )
          else
            Padding(
              padding: const EdgeInsets.fromLTRB(12, 0, 12, 10),
              child: Column(
                children: assignments.map((assignment) {
                  final campus = _text(assignment['campus'], 'Campus');
                  final hod = _text(assignment['hod_name'], 'HOD not available');
                  final email = _text(assignment['hod_email']);
                  return Container(
                    margin: const EdgeInsets.only(bottom: 7),
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      color: _surface,
                      borderRadius: BorderRadius.circular(11),
                      border: Border.all(color: _border),
                    ),
                    child: Row(
                      children: [
                        CircleAvatar(
                          radius: 17,
                          backgroundColor: _standardGold.withOpacity(.12),
                          child: Text(
                            hod.isNotEmpty ? hod[0].toUpperCase() : 'H',
                            style: const TextStyle(
                              color: _standardGold,
                              fontWeight: FontWeight.w900,
                              fontSize: 12,
                            ),
                          ),
                        ),
                        const SizedBox(width: 9),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                campus,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: const TextStyle(
                                  color: _muted,
                                  fontSize: 9.5,
                                  fontWeight: FontWeight.w700,
                                ),
                              ),
                              const SizedBox(height: 2),
                              Text(
                                hod,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: const TextStyle(
                                  color: _ink,
                                  fontSize: 11.5,
                                  fontWeight: FontWeight.w800,
                                ),
                              ),
                              if (email.isNotEmpty)
                                Text(
                                  email,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: const TextStyle(color: _muted, fontSize: 9.5),
                                ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  );
                }).toList(),
              ),
            ),
          const Divider(height: 1, color: _border),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
            child: Row(
              children: [
                Expanded(
                  child: TextButton.icon(
                    onPressed: _dialogOpen ? null : () => _openDepartment(department),
                    icon: const Icon(Icons.edit_outlined, size: 18),
                    label: const Text('EDIT'),
                    style: TextButton.styleFrom(
                      foregroundColor: _darkGreen,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    ),
                  ),
                ),
                const SizedBox(width: 6),
                Expanded(
                  child: TextButton.icon(
                    onPressed: _dialogOpen ? null : () => _delete(department),
                    icon: const Icon(Icons.delete_outline_rounded, size: 18),
                    label: const Text('DELETE'),
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.redAccent,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _MetricData {
  final IconData icon;
  final String value;
  final String label;

  const _MetricData({required this.icon, required this.value, required this.label});
}

class _MetricCard extends StatelessWidget {
  final _MetricData data;

  const _MetricCard({required this.data});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 13),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: _border),
      ),
      child: Row(
        children: [
          Container(
            width: 38,
            height: 38,
            decoration: BoxDecoration(
              color: _darkGreen.withOpacity(.07),
              borderRadius: BorderRadius.circular(11),
            ),
            child: Icon(data.icon, color: _darkGreen, size: 20),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  data.value,
                  style: const TextStyle(color: _ink, fontSize: 17, fontWeight: FontWeight.w900),
                ),
                Text(
                  data.label,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(color: _muted, fontSize: 9.8, fontWeight: FontWeight.w700),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _CoverageBadge extends StatelessWidget {
  final bool complete;
  final int assigned;
  final int campuses;

  const _CoverageBadge({
    required this.complete,
    required this.assigned,
    required this.campuses,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: complete ? const Color(0xFFE4F3E8) : const Color(0xFFFFEDD2),
        borderRadius: BorderRadius.circular(999),
      ),
      child: Text(
        campuses <= 0
            ? 'Campus setup required'
            : '$assigned/$campuses campuses assigned',
        style: TextStyle(
          color: complete ? _darkGreen : const Color(0xFF9A5A00),
          fontSize: 9.3,
          fontWeight: FontWeight.w900,
        ),
      ),
    );
  }
}

class _EmptyDirectory extends StatelessWidget {
  final VoidCallback onAdd;

  const _EmptyDirectory({required this.onAdd});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 460),
        child: Container(
          padding: const EdgeInsets.all(28),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(18),
            border: Border.all(color: _border),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.account_tree_outlined, color: _darkGreen, size: 48),
              const SizedBox(height: 12),
              const Text(
                'No departments registered yet',
                textAlign: TextAlign.center,
                style: TextStyle(color: _ink, fontSize: 16, fontWeight: FontWeight.w900),
              ),
              const SizedBox(height: 6),
              const Text(
                'Create each department once, then assign a different HOD for every campus.',
                textAlign: TextAlign.center,
                style: TextStyle(color: _muted, fontSize: 11.5, height: 1.4),
              ),
              const SizedBox(height: 16),
              ElevatedButton.icon(
                onPressed: onAdd,
                icon: const Icon(Icons.add_rounded),
                label: const Text('ADD DEPARTMENT'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: _standardGold,
                  foregroundColor: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _DirectoryError extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;

  const _DirectoryError({required this.message, required this.onRetry});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(24),
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 520),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.cloud_off_rounded, color: Colors.redAccent, size: 48),
              const SizedBox(height: 12),
              const Text(
                'Unable to load departments',
                style: TextStyle(color: _ink, fontSize: 16, fontWeight: FontWeight.w900),
              ),
              const SizedBox(height: 8),
              SelectableText(
                message,
                textAlign: TextAlign.center,
                style: const TextStyle(color: Colors.redAccent, fontSize: 11.5, height: 1.4),
              ),
              const SizedBox(height: 16),
              OutlinedButton.icon(
                onPressed: onRetry,
                icon: const Icon(Icons.refresh_rounded),
                label: const Text('TRY AGAIN'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _DeleteDepartmentDialog extends StatefulWidget {
  final Map<String, dynamic> department;

  const _DeleteDepartmentDialog({required this.department});

  @override
  State<_DeleteDepartmentDialog> createState() =>
      _DeleteDepartmentDialogState();
}

class _DeleteDepartmentDialogState extends State<_DeleteDepartmentDialog> {
  bool _busy = false;
  String? _error;

  Future<void> _delete() async {
    if (_busy) return;
    setState(() {
      _busy = true;
      _error = null;
    });

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

      await ApiClient.deleteDepartment(id);
      if (mounted) Navigator.of(context).pop(true);
    } catch (error) {
      if (mounted) {
        setState(() => _error = error.toString().replaceFirst('Exception: ', ''));
      }
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.sizeOf(context).width < 520;
    return PopScope(
      canPop: !_busy,
      child: AlertDialog(
        insetPadding: EdgeInsets.symmetric(horizontal: compact ? 12 : 40, vertical: 24),
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
        title: const Row(
          children: [
            Icon(Icons.warning_amber_rounded, color: Colors.redAccent),
            SizedBox(width: 9),
            Expanded(
              child: Text(
                'Remove department',
                style: TextStyle(color: _ink, fontWeight: FontWeight.w900),
              ),
            ),
          ],
        ),
        content: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 460),
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Remove ${widget.department['name'] ?? 'this department'}? Campus HOD assignments will also be removed. Staff must be reassigned to another department before deletion is allowed.',
                  style: const TextStyle(color: _ink, height: 1.45),
                ),
                if (_error != null) ...[
                  const SizedBox(height: 12),
                  SelectableText(
                    _error!,
                    style: const TextStyle(color: Colors.redAccent, fontSize: 11.5),
                  ),
                ],
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: _busy ? null : () => Navigator.of(context).pop(false),
            child: const Text('CANCEL'),
          ),
          ElevatedButton.icon(
            onPressed: _busy ? null : _delete,
            icon: _busy
                ? const SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                  )
                : const Icon(Icons.delete_outline_rounded),
            label: Text(_busy ? 'DELETING...' : 'DELETE'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.redAccent,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }
}
