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

import 'dart:convert';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import '../../../../../core/networks/api_client.dart';

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

class AddDepartmentDialog extends StatefulWidget {
  final dynamic departmentToEdit;

  const AddDepartmentDialog({super.key, this.departmentToEdit});

  @override
  State<AddDepartmentDialog> createState() => _AddDepartmentDialogState();
}

class _AddDepartmentDialogState extends State<AddDepartmentDialog> {
  final _formKey = GlobalKey<FormState>();

  late final TextEditingController _nameController;
  late final TextEditingController _descriptionController;

  bool _isLoading = false;
  bool _setupLoading = true;
  String? _error;
  String? _setupError;

  List<String> _campuses = <String>[];
  List<Map<String, dynamic>> _candidates = <Map<String, dynamic>>[];
  final Map<String, int?> _hodByCampus = <String, int?>{};

  bool get _isEditing => widget.departmentToEdit != null;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(
      text: widget.departmentToEdit?['name']?.toString() ?? '',
    );
    _descriptionController = TextEditingController(
      text: widget.departmentToEdit?['description']?.toString() ?? '',
    );
    _loadSetup();
  }

  @override
  void dispose() {
    _nameController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

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

  String _campusKey(String value) {
    final n = value.trim().toUpperCase().replaceAll(RegExp(r'\s+'), ' ');
    if (n.contains('MANSA')) return 'MANSA';
    if (n.contains('NDOLA')) return 'NDOLA';
    if (n.contains('CHIPATA')) return 'CHIPATA';
    if (n.contains('LIVINGSTONE')) return 'LIVINGSTONE';
    if (n.contains('E-LEARNING') || n.contains('ELEARNING') || n.contains('ONLINE')) {
      return 'E-LEARNING';
    }
    if (n.contains('10 MILES') || n.contains('TEN MILES')) return '10 MILES';
    if (n == 'HQ' ||
        n == 'HQ CAMPUS' ||
        n.contains('HEAD QUART') ||
        n.contains('HEADQUART') ||
        n.contains('HEAD OFFICE')) {
      return 'HQ';
    }
    return n;
  }

  Future<void> _loadSetup() async {
    if (!mounted) return;
    setState(() {
      _setupLoading = true;
      _setupError = null;
    });

    try {
      final uri = Uri.parse('${ApiClient.baseUrl}/api/departments.php').replace(
        queryParameters: const {'action': 'setup'},
      );
      final response = await ApiClient.offlineFirstGet(uri, headers: await ApiClient.getHeaders(), forceRefresh: true)
          .timeout(const Duration(seconds: 18));
      await ApiClient.handleUnauthorized(response);

      if (response.statusCode != 200) {
        String detail = response.body;
        try {
          final decoded = jsonDecode(response.body);
          if (decoded is Map) {
            detail = _text(decoded['detail'], _text(decoded['message'], response.body));
          }
        } catch (_) {}
        throw Exception(detail.isEmpty
            ? 'Department setup could not be loaded.'
            : detail);
      }

      final decoded = jsonDecode(response.body);
      if (decoded is! Map) {
        throw const FormatException('Department setup response is invalid.');
      }

      final campusRaw = decoded['campuses'];
      final candidateRaw = decoded['candidates'];

      final campuses = <String>[];
      if (campusRaw is List) {
        final seen = <String>{};
        for (final item in campusRaw) {
          final campus = _text(item is Map ? item['name'] ?? item['campus'] : item);
          if (campus.isEmpty) continue;
          final key = _campusKey(campus);
          if (seen.add(key)) campuses.add(campus);
        }
      }
      campuses.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));

      final candidates = <Map<String, dynamic>>[];
      final candidateIds = <int>{};
      if (candidateRaw is List) {
        for (final item in candidateRaw) {
          if (item is! Map) continue;
          final row = item.map((k, v) => MapEntry(k.toString(), v));
          final id = int.tryParse('${row['id'] ?? ''}') ?? 0;
          final campus = _text(row['campus']);
          if (id <= 0 || campus.isEmpty || !candidateIds.add(id)) continue;
          candidates.add(row);
        }
      }
      candidates.sort((a, b) {
        final campusCompare = _text(a['campus'])
            .toLowerCase()
            .compareTo(_text(b['campus']).toLowerCase());
        if (campusCompare != 0) return campusCompare;
        return _candidateName(a)
            .toLowerCase()
            .compareTo(_candidateName(b).toLowerCase());
      });

      final existingAssignments = <String, int>{};
      final rawAssignments = widget.departmentToEdit?['hod_assignments'];
      if (rawAssignments is List) {
        for (final raw in rawAssignments) {
          if (raw is! Map) continue;
          final campus = _text(raw['campus']);
          final userId = int.tryParse('${raw['user_id'] ?? ''}') ?? 0;
          if (campus.isNotEmpty && userId > 0) {
            existingAssignments[_campusKey(campus)] = userId;
          }
        }
      }

      final selection = <String, int?>{};
      for (final campus in campuses) {
        final key = _campusKey(campus);
        final existing = existingAssignments[key];
        final valid = existing != null &&
            candidates.any((candidate) =>
                (int.tryParse('${candidate['id'] ?? ''}') ?? 0) == existing &&
                _campusKey(_text(candidate['campus'])) == key);
        selection[key] = valid ? existing : null;
      }

      if (!mounted) return;
      setState(() {
        _campuses = campuses;
        _candidates = candidates;
        _hodByCampus
          ..clear()
          ..addAll(selection);
        _setupLoading = false;
      });
    } catch (error) {
      if (!mounted) return;
      setState(() {
        _setupLoading = false;
        _setupError = error.toString().replaceFirst('Exception: ', '');
      });
    }
  }

  String _candidateName(Map<String, dynamic> candidate) {
    return _text(candidate['full_name'],
        _text(candidate['name'], _text(candidate['email'], 'Unnamed staff member')));
  }

  String _candidateSubtitle(Map<String, dynamic> candidate) {
    final parts = <String>[];
    final position = _text(candidate['position']);
    final role = _text(candidate['role']);
    final email = _text(candidate['email']);
    if (position.isNotEmpty) {
      parts.add(position);
    } else if (role.isNotEmpty) {
      parts.add(role);
    }
    if (email.isNotEmpty) parts.add(email);
    return parts.join(' • ');
  }

  List<Map<String, dynamic>> _candidatesForCampus(String campus) {
    final key = _campusKey(campus);
    return _candidates
        .where((candidate) => _campusKey(_text(candidate['campus'])) == key)
        .toList();
  }

  bool get _allCampusesAssigned {
    if (_campuses.isEmpty) return false;
    return _campuses.every((campus) {
      final id = _hodByCampus[_campusKey(campus)];
      return id != null && id > 0;
    });
  }

  Future<void> _submitForm() async {
    if (_isLoading || _setupLoading) return;
    if (!(_formKey.currentState?.validate() ?? false)) return;

    if (_campuses.isEmpty) {
      setState(() => _error =
          'No campuses are available. Register campuses before saving a department.');
      return;
    }

    final missing = _campuses
        .where((campus) => (_hodByCampus[_campusKey(campus)] ?? 0) <= 0)
        .toList();
    if (missing.isNotEmpty) {
      setState(() => _error =
          'Assign an HOD for every campus before saving. Missing: ${missing.join(', ')}.');
      return;
    }

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

    final payload = <String, dynamic>{
      'name': _nameController.text.trim(),
      'description': _descriptionController.text.trim(),
      'hod_assignments': _campuses
          .map((campus) => <String, dynamic>{
                'campus': campus,
                'user_id': _hodByCampus[_campusKey(campus)],
              })
          .toList(),
    };

    try {
      if (!_isEditing) {
        await ApiClient.createDepartment(payload);
      } else {
        final id = int.tryParse(widget.departmentToEdit['id']?.toString() ?? '');
        if (id == null || id <= 0) {
          throw Exception('Invalid department ID. Reload the directory.');
        }
        await ApiClient.updateDepartment(id, payload);
      }

      if (mounted) Navigator.of(context).pop(true);
    } catch (error) {
      if (mounted) {
        setState(() {
          _error = 'Failed to save department: '
              '${error.toString().replaceFirst('Exception: ', '')}';
        });
      }
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final media = MediaQuery.of(context);
    final screenWidth = media.size.width;
    final compact = screenWidth < 640;
    final horizontalInset = compact ? 8.0 : (screenWidth < 1000 ? 24.0 : 48.0);
    final maxWidth = math.min(1080.0, math.max(320.0, screenWidth - (horizontalInset * 2)));

    return PopScope(
      canPop: !_isLoading,
      child: Dialog(
        insetPadding: EdgeInsets.symmetric(
          horizontal: horizontalInset,
          vertical: compact ? 8 : 22,
        ),
        backgroundColor: Colors.transparent,
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxWidth: maxWidth,
            maxHeight: media.size.height * (compact ? 0.97 : 0.93),
          ),
          child: Material(
            color: Colors.white,
            elevation: 18,
            clipBehavior: Clip.antiAlias,
            borderRadius: BorderRadius.circular(compact ? 16 : 22),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                _buildHeader(compact),
                Expanded(
                  child: _setupLoading
                      ? const Center(
                          child: CircularProgressIndicator(color: _darkGreen),
                        )
                      : _setupError != null
                          ? _buildSetupError()
                          : SingleChildScrollView(
                              padding: EdgeInsets.fromLTRB(
                                compact ? 16 : 28,
                                compact ? 18 : 26,
                                compact ? 16 : 28,
                                28,
                              ),
                              child: Form(
                                key: _formKey,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.stretch,
                                  children: [
                                    if (_error != null) ...[
                                      _ErrorPanel(message: _error!),
                                      const SizedBox(height: 18),
                                    ],
                                    _InfoBanner(compact: compact),
                                    const SizedBox(height: 22),
                                    _sectionTitle(
                                      icon: Icons.account_tree_rounded,
                                      title: 'Department details',
                                      subtitle:
                                          'Create the department once. It will be available university-wide.',
                                    ),
                                    const SizedBox(height: 14),
                                    LayoutBuilder(
                                      builder: (context, constraints) {
                                        final stack = constraints.maxWidth < 720;
                                        final nameField = _buildTextField(
                                          controller: _nameController,
                                          label: 'Department Name',
                                          hint: 'e.g. Computer Science',
                                          icon: Icons.apartment_rounded,
                                          validator: (value) =>
                                              value == null || value.trim().isEmpty
                                                  ? 'Department Name is required'
                                                  : null,
                                        );
                                        final descriptionField = _buildTextField(
                                          controller: _descriptionController,
                                          label: 'Department Description / Info',
                                          hint:
                                              'Briefly describe the academic or administrative function of this department.',
                                          icon: Icons.notes_rounded,
                                          maxLines: 4,
                                        );
                                        if (stack) {
                                          return Column(
                                            children: [
                                              nameField,
                                              const SizedBox(height: 14),
                                              descriptionField,
                                            ],
                                          );
                                        }
                                        return Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Expanded(child: nameField),
                                            const SizedBox(width: 16),
                                            Expanded(child: descriptionField),
                                          ],
                                        );
                                      },
                                    ),
                                    const SizedBox(height: 28),
                                    _sectionTitle(
                                      icon: Icons.supervisor_account_rounded,
                                      title: 'Campus HOD assignments',
                                      subtitle:
                                          'The department is shared by the whole university, but every campus must have its own Head of Department.',
                                    ),
                                    const SizedBox(height: 8),
                                    _coverageStrip(),
                                    const SizedBox(height: 14),
                                    _buildHodGrid(),
                                  ],
                                ),
                              ),
                            ),
                ),
                _buildFooter(compact),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHeader(bool compact) {
    return Container(
      padding: EdgeInsets.fromLTRB(compact ? 16 : 24, 16, 10, 16),
      decoration: const BoxDecoration(
        color: _darkGreen,
        border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
      ),
      child: Row(
        children: [
          Container(
            width: compact ? 40 : 46,
            height: compact ? 40 : 46,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(.12),
              borderRadius: BorderRadius.circular(13),
              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(
                  _isEditing ? 'EDIT DEPARTMENT' : 'REGISTER DEPARTMENT',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: compact ? 15 : 18,
                    fontWeight: FontWeight.w900,
                    letterSpacing: .8,
                  ),
                ),
                const SizedBox(height: 3),
                Text(
                  'University-wide department • campus-specific HOD leadership',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white.withOpacity(.78),
                    fontSize: compact ? 10 : 11.5,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
          IconButton(
            tooltip: 'Close',
            icon: const Icon(Icons.close_rounded, color: Colors.white),
            onPressed: _isLoading ? null : () => Navigator.of(context).pop(false),
          ),
        ],
      ),
    );
  }

  Widget _buildSetupError() {
    return Center(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(28),
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 560),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.cloud_off_rounded, size: 48, color: Colors.redAccent),
              const SizedBox(height: 14),
              const Text(
                'Department setup could not be loaded',
                textAlign: TextAlign.center,
                style: TextStyle(color: _ink, fontSize: 17, fontWeight: FontWeight.w900),
              ),
              const SizedBox(height: 8),
              Text(
                _setupError ?? 'Unknown setup error.',
                textAlign: TextAlign.center,
                style: const TextStyle(color: _muted, height: 1.45),
              ),
              const SizedBox(height: 18),
              ElevatedButton.icon(
                onPressed: _loadSetup,
                icon: const Icon(Icons.refresh_rounded),
                label: const Text('RETRY'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: _darkGreen,
                  foregroundColor: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _sectionTitle({
    required IconData icon,
    required String title,
    required String subtitle,
  }) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: 38,
          height: 38,
          decoration: BoxDecoration(
            color: _darkGreen.withOpacity(.08),
            borderRadius: BorderRadius.circular(11),
          ),
          child: Icon(icon, color: _darkGreen, size: 21),
        ),
        const SizedBox(width: 11),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: const TextStyle(
                  color: _ink,
                  fontSize: 15,
                  fontWeight: FontWeight.w900,
                ),
              ),
              const SizedBox(height: 3),
              Text(
                subtitle,
                style: const TextStyle(color: _muted, fontSize: 11.5, height: 1.4),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _coverageStrip() {
    final assigned = _campuses
        .where((campus) => (_hodByCampus[_campusKey(campus)] ?? 0) > 0)
        .length;
    final complete = _campuses.isNotEmpty && assigned == _campuses.length;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 11),
      decoration: BoxDecoration(
        color: complete ? const Color(0xFFEFF8F2) : const Color(0xFFFFF7EA),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: complete ? const Color(0xFFB9DEC7) : const Color(0xFFF0D5A3),
        ),
      ),
      child: Row(
        children: [
          Icon(
            complete ? Icons.verified_rounded : Icons.info_outline_rounded,
            color: complete ? _darkGreen : _standardGold,
            size: 20,
          ),
          const SizedBox(width: 9),
          Expanded(
            child: Text(
              _campuses.isEmpty
                  ? 'No campuses are registered.'
                  : '$assigned of ${_campuses.length} campuses have an HOD selected.',
              style: const TextStyle(color: _ink, fontSize: 11.5, fontWeight: FontWeight.w700),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHodGrid() {
    if (_campuses.isEmpty) {
      return const _EmptyPanel(
        icon: Icons.location_off_outlined,
        title: 'No campuses available',
        message: 'Create the university campuses first, then return here to register the department.',
      );
    }

    return LayoutBuilder(
      builder: (context, constraints) {
        final twoColumns = constraints.maxWidth >= 760;
        final spacing = 14.0;
        final cardWidth = twoColumns
            ? (constraints.maxWidth - spacing) / 2
            : constraints.maxWidth;

        return Wrap(
          spacing: spacing,
          runSpacing: spacing,
          children: _campuses
              .map((campus) => SizedBox(
                    width: cardWidth,
                    child: _hodCard(campus),
                  ))
              .toList(),
        );
      },
    );
  }

  Widget _hodCard(String campus) {
    final key = _campusKey(campus);
    final candidates = _candidatesForCampus(campus);
    final selected = _hodByCampus[key];
    final selectedExists = selected != null &&
        candidates.any((candidate) =>
            (int.tryParse('${candidate['id'] ?? ''}') ?? 0) == selected);

    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(15),
        border: Border.all(
          color: selectedExists ? _darkGreen.withOpacity(.22) : _border,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(.025),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              Container(
                width: 36,
                height: 36,
                decoration: BoxDecoration(
                  color: _standardGold.withOpacity(.10),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(Icons.location_city_rounded, color: _standardGold, size: 19),
              ),
              const SizedBox(width: 10),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      campus,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(
                        color: _ink,
                        fontSize: 12.5,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      selectedExists ? 'HOD assigned' : 'HOD required',
                      style: TextStyle(
                        color: selectedExists ? _darkGreen : Colors.redAccent,
                        fontSize: 10.5,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          if (candidates.isEmpty)
            Container(
              padding: const EdgeInsets.all(11),
              decoration: BoxDecoration(
                color: const Color(0xFFFFF1F0),
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: const Color(0xFFF4C7C3)),
              ),
              child: const Text(
                'No staff account is available at this campus. Add or assign staff to this campus before creating the department.',
                style: TextStyle(color: Color(0xFF9D2D24), fontSize: 10.8, height: 1.35),
              ),
            )
          else
            DropdownButtonFormField<int>(
              value: selectedExists ? selected : null,
              isExpanded: true,
              decoration: InputDecoration(
                labelText: 'Head of Department (HOD)',
                prefixIcon: const Icon(Icons.person_pin_rounded, color: _darkGreen),
                filled: true,
                fillColor: _surface,
                contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 13),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(11),
                  borderSide: const BorderSide(color: _border),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(11),
                  borderSide: const BorderSide(color: _border),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(11),
                  borderSide: const BorderSide(color: _darkGreen, width: 1.5),
                ),
              ),
              items: candidates.map((candidate) {
                final id = int.tryParse('${candidate['id'] ?? ''}') ?? 0;
                final name = _candidateName(candidate);
                final subtitle = _candidateSubtitle(candidate);
                return DropdownMenuItem<int>(
                  value: id,
                  child: Tooltip(
                    message: subtitle.isEmpty ? name : '$name\n$subtitle',
                    child: Text(
                      subtitle.isEmpty ? name : '$name — $subtitle',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontSize: 11.5, color: _ink),
                    ),
                  ),
                );
              }).toList(),
              onChanged: _isLoading
                  ? null
                  : (value) => setState(() => _hodByCampus[key] = value),
              validator: (_) => (_hodByCampus[key] ?? 0) <= 0
                  ? 'Select an HOD for $campus'
                  : null,
            ),
        ],
      ),
    );
  }

  Widget _buildFooter(bool compact) {
    final saveButton = ElevatedButton.icon(
      onPressed: _isLoading || _setupLoading || !_allCampusesAssigned
          ? null
          : _submitForm,
      icon: _isLoading
          ? const SizedBox(
              width: 18,
              height: 18,
              child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
            )
          : const Icon(Icons.save_rounded),
      label: Text(
        _isLoading
            ? 'SAVING...'
            : (_isEditing ? 'UPDATE DEPARTMENT' : 'SAVE DEPARTMENT'),
        style: const TextStyle(fontWeight: FontWeight.w900, letterSpacing: .5),
      ),
      style: ElevatedButton.styleFrom(
        backgroundColor: _standardGold,
        foregroundColor: Colors.white,
        disabledBackgroundColor: Colors.grey.shade300,
        disabledForegroundColor: Colors.grey.shade600,
        elevation: 0,
        padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 16),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(11)),
      ),
    );

    final cancelButton = OutlinedButton(
      onPressed: _isLoading ? null : () => Navigator.of(context).pop(false),
      style: OutlinedButton.styleFrom(
        foregroundColor: _ink,
        side: const BorderSide(color: _border),
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(11)),
      ),
      child: const Text('CANCEL', style: TextStyle(fontWeight: FontWeight.w800)),
    );

    return Container(
      padding: EdgeInsets.fromLTRB(compact ? 14 : 24, 12, compact ? 14 : 24, 14),
      decoration: const BoxDecoration(
        color: _surface,
        border: Border(top: BorderSide(color: _border)),
      ),
      child: compact
          ? Row(
              children: [
                Expanded(child: cancelButton),
                const SizedBox(width: 10),
                Expanded(flex: 2, child: saveButton),
              ],
            )
          : Row(
              children: [
                Expanded(
                  child: Text(
                    _allCampusesAssigned
                        ? 'Ready to save: every campus has an HOD.'
                        : 'Select one HOD for every campus to continue.',
                    style: TextStyle(
                      color: _allCampusesAssigned ? _darkGreen : _muted,
                      fontSize: 11.5,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),
                cancelButton,
                const SizedBox(width: 10),
                saveButton,
              ],
            ),
    );
  }

  Widget _buildTextField({
    required TextEditingController controller,
    required String label,
    required String hint,
    required IconData icon,
    int maxLines = 1,
    String? Function(String?)? validator,
  }) {
    return TextFormField(
      controller: controller,
      enabled: !_isLoading,
      style: const TextStyle(color: _ink, fontSize: 13),
      validator: validator,
      cursorColor: _darkGreen,
      maxLines: maxLines,
      decoration: InputDecoration(
        labelText: label,
        hintText: hint,
        alignLabelWithHint: maxLines > 1,
        prefixIcon: Icon(icon, color: _darkGreen.withOpacity(.72), size: 20),
        filled: true,
        fillColor: _surface,
        contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 16),
        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: _darkGreen, width: 1.5),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Colors.redAccent),
        ),
      ),
    );
  }
}

class _InfoBanner extends StatelessWidget {
  final bool compact;

  const _InfoBanner({required this.compact});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(compact ? 13 : 16),
      decoration: BoxDecoration(
        color: const Color(0xFFEFF7F2),
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: const Color(0xFFC9E1D2)),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Icon(Icons.hub_rounded, color: _darkGreen, size: 21),
          const SizedBox(width: 10),
          const Expanded(
            child: Text(
              'ONE DEPARTMENT, UNIVERSITY-WIDE. The department record is created once and shared by all campuses. Leadership is campus-specific, so each campus must have its own HOD assignment.',
              style: TextStyle(
                color: _ink,
                fontSize: 11.5,
                height: 1.45,
                fontWeight: FontWeight.w700,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _ErrorPanel extends StatelessWidget {
  final String message;

  const _ErrorPanel({required this.message});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(13),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF1F0),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: const Color(0xFFF3C4BF)),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Icon(Icons.error_outline_rounded, color: Colors.redAccent, size: 20),
          const SizedBox(width: 9),
          Expanded(
            child: SelectableText(
              message,
              style: const TextStyle(color: Color(0xFF9D2D24), fontSize: 11.5, height: 1.4),
            ),
          ),
        ],
      ),
    );
  }
}

class _EmptyPanel extends StatelessWidget {
  final IconData icon;
  final String title;
  final String message;

  const _EmptyPanel({
    required this.icon,
    required this.title,
    required this.message,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: _surface,
        borderRadius: BorderRadius.circular(15),
        border: Border.all(color: _border),
      ),
      child: Column(
        children: [
          Icon(icon, color: _muted, size: 34),
          const SizedBox(height: 10),
          Text(title, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900)),
          const SizedBox(height: 5),
          Text(
            message,
            textAlign: TextAlign.center,
            style: const TextStyle(color: _muted, fontSize: 11.5, height: 1.4),
          ),
        ],
      ),
    );
  }
}
