import 'package:flutter/material.dart';

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

const Color _green = Color.fromARGB(255, 2, 105, 48);
const Color _gold = Color.fromARGB(255, 204, 117, 4);
const Color _ink = Color(0xFF18241E);
const Color _muted = Color(0xFF66736C);
const Color _surface = Color(0xFFF4F7F5);
const Color _border = Color(0xFFE0E7E3);

class RoutingDirectorySubTab extends StatefulWidget {
  final VoidCallback? onChanged;

  const RoutingDirectorySubTab({super.key, this.onChanged});

  @override
  State<RoutingDirectorySubTab> createState() => _RoutingDirectorySubTabState();
}

class _RoutingDirectorySubTabState extends State<RoutingDirectorySubTab> {
  final _search = TextEditingController();

  /// Directory for the campus selected in the UI. Only its Registrar is used.
  Map<String, dynamic> _directory = const {};

  /// Institutional routing directory. DVC1, Accountant, CFO and CEO are always
  /// resolved from Head Quarters regardless of the request origin campus.
  Map<String, dynamic> _hqDirectory = const {};

  bool _loading = true;
  String? _error;
  String? _campus;
  String _hqCampus = 'Head Quarters';

  @override
  void initState() {
    super.initState();
    _search.addListener(() => setState(() {}));
    _load();
  }

  @override
  void dispose() {
    _search.dispose();
    super.dispose();
  }

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

  bool _isHeadquartersLabel(String value) {
    final clean = value.trim().toUpperCase().replaceAll('-', ' ');
    return clean == 'HQ' ||
        clean.contains('HEAD QUARTER') ||
        clean.contains('HEADQUARTER');
  }

  List<String> _campusLabels(Map<String, dynamic> directory) {
    final raw = directory['campuses'];
    if (raw is! List) return const [];
    return raw
        .map((e) => e.toString().trim())
        .where((e) => e.isNotEmpty)
        .toSet()
        .toList();
  }

  String _discoverHeadquartersLabel(Map<String, dynamic> directory) {
    for (final campus in _campusLabels(directory)) {
      if (_isHeadquartersLabel(campus)) return campus;
    }
    final selected = '${directory['selected_campus'] ?? ''}'.trim();
    if (_isHeadquartersLabel(selected)) return selected;
    return 'Head Quarters';
  }

  Future<Map<String, dynamic>> _fetchHeadquartersDirectory(
    Map<String, dynamic> campusDirectory,
  ) async {
    final candidates = <String>[
      _discoverHeadquartersLabel(campusDirectory),
      'Head Quarters',
      'HQ',
      'Headquarters',
    ];
    Object? lastError;
    for (final candidate in candidates.toSet()) {
      try {
        final result = await RequestWorkflowService.getOfficeHolders(campus: candidate);
        final selected = '${result['selected_campus'] ?? candidate}'.trim();
        if (_isHeadquartersLabel(selected) || _isHeadquartersLabel(candidate)) {
          _hqCampus = selected.isEmpty ? candidate : selected;
          return result;
        }
      } catch (e) {
        lastError = e;
      }
    }
    throw StateError(
      'Head Quarters routing directory could not be loaded. '
      '${lastError == null ? 'Register the Head Quarters campus first.' : RequestWorkflowService.cleanError(lastError)}',
    );
  }

  Future<void> _load({String? campus}) async {
    if (mounted) {
      setState(() {
        _loading = true;
        _error = null;
      });
    }

    try {
      final campusDirectory = await RequestWorkflowService.getOfficeHolders(
        campus: campus ?? _campus,
      );
      final selectedCampus = '${campusDirectory['selected_campus'] ?? campus ?? _campus ?? ''}'.trim();

      Map<String, dynamic> headquartersDirectory;
      if (_isHeadquartersLabel(selectedCampus)) {
        headquartersDirectory = campusDirectory;
        _hqCampus = selectedCampus.isEmpty ? 'Head Quarters' : selectedCampus;
      } else {
        headquartersDirectory = await _fetchHeadquartersDirectory(campusDirectory);
      }

      if (!mounted) return;
      setState(() {
        _directory = campusDirectory;
        _hqDirectory = headquartersDirectory;
        _campus = selectedCampus;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = RequestWorkflowService.cleanError(e);
      });
    }
  }

  bool _canManageDirectory(Map<String, dynamic> directory) =>
      _truthy(directory['can_manage']);

  bool get _canManage =>
      _canManageDirectory(_directory) || _canManageDirectory(_hqDirectory);

  List<String> get _campuses {
    final values = <String>{..._campusLabels(_directory), ..._campusLabels(_hqDirectory)};
    if ((_campus ?? '').trim().isNotEmpty) values.add(_campus!.trim());
    final rows = values.toList()
      ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    return rows;
  }

  List<Map<String, dynamic>> _positionRows(Map<String, dynamic> directory) {
    final raw = directory['positions'];
    if (raw is! List) return const [];
    return raw
        .whereType<Map>()
        .map((e) => e.map((k, v) => MapEntry(k.toString(), v)))
        .toList();
  }

  List<Map<String, dynamic>> _eligibleRows(Map<String, dynamic> directory) {
    final raw = directory['eligible_users'];
    if (raw is! List) return const [];
    return raw
        .whereType<Map>()
        .map((e) => e.map((k, v) => MapEntry(k.toString(), v)))
        .toList();
  }

  bool _isCentralStage(String stage) =>
      stage == 'dvc1' || stage == 'accountant' || stage == 'cfo' || stage == 'ceo';

  String _routingCampusForPosition(Map<String, dynamic> position) {
    final stage = '${position['stage'] ?? ''}'.trim().toLowerCase();
    return _isCentralStage(stage) ? _hqCampus : (_campus ?? '');
  }

  bool _canManagePosition(Map<String, dynamic> position) {
    final stage = '${position['stage'] ?? ''}'.trim().toLowerCase();
    return _canManageDirectory(_isCentralStage(stage) ? _hqDirectory : _directory);
  }

  List<Map<String, dynamic>> _eligibleUsersForPosition(Map<String, dynamic> position) {
    final stage = '${position['stage'] ?? ''}'.trim().toLowerCase();
    final source = _isCentralStage(stage) ? _hqDirectory : _directory;
    return _eligibleRows(source).where((user) {
      return '${user['position_key'] ?? ''}'.trim().toLowerCase() == stage;
    }).toList();
  }

  List<Map<String, dynamic>> get _positions {
    final localRegistrar = _positionRows(_directory)
        .where((row) => '${row['stage'] ?? ''}'.trim().toLowerCase() == 'registrar')
        .map((row) => <String, dynamic>{
              ...row,
              'routing_campus': _campus ?? row['campus'],
              'scope_label': 'CAMPUS OFFICE',
            });

    final headquartersOffices = _positionRows(_hqDirectory)
        .where((row) => _isCentralStage('${row['stage'] ?? ''}'.trim().toLowerCase()))
        .map((row) => <String, dynamic>{
              ...row,
              'routing_campus': _hqCampus,
              'scope_label': 'HEAD QUARTERS',
            });

    final query = _search.text.trim().toLowerCase();
    return <Map<String, dynamic>>[
      ...localRegistrar,
      ...headquartersOffices,
    ].where((row) {
      if (query.isEmpty) return true;
      final haystack = [
        row['position_title'],
        row['holder_name'],
        row['holder_email'],
        row['holder_role'],
        row['routing_campus'],
        row['scope_label'],
      ].map((e) => '${e ?? ''}'.toLowerCase()).join(' ');
      return haystack.contains(query);
    }).toList();
  }

  int get _assignedCount => _positions.where((e) => e['user_id'] != null).length;

  Future<void> _assign(Map<String, dynamic> position) async {
    if (!_canManagePosition(position)) return;
    if ((_campus ?? '').isEmpty) {
      _snack('Select a campus first.', error: true);
      return;
    }

    final requiredStage = '${position['stage'] ?? ''}'.trim().toLowerCase();
    final assignmentCampus = _routingCampusForPosition(position);
    final matchingAdmins = _eligibleUsersForPosition(position);

    if (matchingAdmins.isEmpty) {
      final officeDescription = requiredStage == 'registrar'
          ? 'the selected campus'
          : 'Head Quarters';
      _snack(
        'No administrator at $officeDescription has the database position '
        '${position['position_title'] ?? 'required for this route'}. '
        'Assign that administrator to $assignmentCampus first.',
        error: true,
      );
      return;
    }

    final selected = await showDialog<int>(
      context: context,
      barrierDismissible: true,
      builder: (_) => _AssignHolderDialog(
        campus: assignmentCampus,
        position: '${position['position_title'] ?? 'Position'}',
        currentUserId: int.tryParse('${position['user_id'] ?? ''}'),
        users: matchingAdmins,
      ),
    );
    if (selected == null) return;

    try {
      final result = await RequestWorkflowService.assignOfficeHolder(
        positionId: int.parse('${position['position_id']}'),
        userId: selected,
        campus: assignmentCampus,
      );
      if (!mounted) return;
      _snack('${result['message'] ?? 'Office holder assigned.'}');
      await _load(campus: _campus);
      widget.onChanged?.call();
    } catch (e) {
      if (!mounted) return;
      _snack(RequestWorkflowService.cleanError(e), error: true);
    }
  }

  Future<void> _remove(Map<String, dynamic> position) async {
    final assignmentId = int.tryParse('${position['assignment_id'] ?? ''}');
    if (!_canManagePosition(position) || assignmentId == null) return;
    final routingCampus = _routingCampusForPosition(position);
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: const Text('Remove routing holder?'),
        content: Text(
          '${position['holder_name'] ?? 'This staff member'} will no longer receive requests routed to '
          '${position['position_title']} at $routingCampus.',
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),
          FilledButton(
            onPressed: () => Navigator.pop(ctx, true),
            style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700),
            child: const Text('Remove'),
          ),
        ],
      ),
    );
    if (confirmed != true) return;

    try {
      await RequestWorkflowService.removeOfficeHolder(assignmentId);
      if (!mounted) return;
      _snack('Routing holder removed.');
      await _load(campus: _campus);
      widget.onChanged?.call();
    } catch (e) {
      if (!mounted) return;
      _snack(RequestWorkflowService.cleanError(e), error: true);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final compact = constraints.maxWidth < 680;
        final horizontal = constraints.maxWidth >= 980
            ? (constraints.maxWidth - 940) / 2
            : compact
                ? 12.0
                : 20.0;

        if (_loading && _directory.isEmpty) {
          return const Center(child: CircularProgressIndicator(color: _green));
        }
        if (_error != null && _directory.isEmpty) {
          return _DirectoryError(message: _error!, onRetry: _load);
        }

        final positions = _positions;
        return RefreshIndicator(
          color: _green,
          onRefresh: _load,
          child: ListView(
            physics: const AlwaysScrollableScrollPhysics(),
            padding: EdgeInsets.fromLTRB(horizontal, 14, horizontal, 100),
            children: [
              _DirectoryHero(
                compact: compact,
                campus: _campus ?? 'Campus',
                assigned: _assignedCount,
                total: positions.length,
                canManage: _canManage,
                hqCampus: _hqCampus,
              ),
              const SizedBox(height: 12),
              _DirectoryToolbar(
                compact: compact,
                controller: _search,
                campus: _campus,
                campuses: _campuses,
                canChooseCampus: _campuses.length > 1,
                onCampus: (value) {
                  if (value == null || value == _campus) return;
                  _campus = value;
                  _load(campus: value);
                },
                onRefresh: _load,
              ),
              if (_error != null) ...[
                const SizedBox(height: 10),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.red.shade50,
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Colors.red.shade100),
                  ),
                  child: Text(_error!, style: TextStyle(color: Colors.red.shade800, fontSize: 11.5)),
                ),
              ],
              const SizedBox(height: 14),
              if (positions.isEmpty)
                const _DirectoryEmpty()
              else
                ...positions.map(
                  (row) => Padding(
                    padding: const EdgeInsets.only(bottom: 10),
                    child: _PositionHolderCard(
                      data: row,
                      compact: compact,
                      canManage: _canManagePosition(row),
                      onAssign: () => _assign(row),
                      onRemove: () => _remove(row),
                    ),
                  ),
                ),
            ],
          ),
        );
      },
    );
  }
}

class _DirectoryHero extends StatelessWidget {
  final bool compact;
  final String campus;
  final int assigned;
  final int total;
  final bool canManage;
  final String hqCampus;

  const _DirectoryHero({
    required this.compact,
    required this.campus,
    required this.assigned,
    required this.total,
    required this.canManage,
    required this.hqCampus,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(compact ? 16 : 20),
      decoration: BoxDecoration(
        color: _green,
        borderRadius: BorderRadius.circular(18),
        boxShadow: [BoxShadow(color: _green.withOpacity(0.14), blurRadius: 18, offset: const Offset(0, 8))],
      ),
      child: compact
          ? Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _heroText(),
                const SizedBox(height: 14),
                Row(children: [Expanded(child: _heroMetric('$assigned', 'Assigned')), const SizedBox(width: 8), Expanded(child: _heroMetric('$total', 'Workflow offices'))]),
              ],
            )
          : Row(
              children: [
                Expanded(child: _heroText()),
                _heroMetric('$assigned', 'Assigned'),
                const SizedBox(width: 10),
                _heroMetric('$total', 'Workflow offices'),
              ],
            ),
    );
  }

  Widget _heroText() => Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(width: 42, height: 42, decoration: BoxDecoration(color: Colors.white.withOpacity(0.12), borderRadius: BorderRadius.circular(12)), child: const Icon(Icons.badge_outlined, color: Colors.white)),
              const SizedBox(width: 11),
              const Expanded(child: Text('ROUTING OFFICE DIRECTORY', style: TextStyle(color: Colors.white, fontSize: 15, fontWeight: FontWeight.w900, letterSpacing: 0.7))),
            ],
          ),
          const SizedBox(height: 10),
          Text(
            canManage
                ? 'Configure the Registrar for $campus. DVC1, Accountant, CFO and CEO are central institutional offices and are configured only under $hqCampus. Every request leaves its campus after Registrar approval and continues through Head Quarters.'
                : 'Registrar access is campus-specific for $campus. DVC1, Accountant, CFO and CEO are resolved only from $hqCampus for all campuses.',
            style: const TextStyle(color: Color(0xFFE0EFE6), fontSize: 11.5, height: 1.45),
          ),
        ],
      );

  Widget _heroMetric(String value, String label) => Container(
        constraints: const BoxConstraints(minWidth: 88),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(color: Colors.white.withOpacity(0.10), borderRadius: BorderRadius.circular(12)),
        child: Column(children: [Text(value, style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w900)), Text(label, style: const TextStyle(color: Color(0xFFDDECE3), fontSize: 9.5, fontWeight: FontWeight.w700))]),
      );
}

class _DirectoryToolbar extends StatelessWidget {
  final bool compact;
  final TextEditingController controller;
  final String? campus;
  final List<String> campuses;
  final bool canChooseCampus;
  final ValueChanged<String?> onCampus;
  final VoidCallback onRefresh;

  const _DirectoryToolbar({
    required this.compact,
    required this.controller,
    required this.campus,
    required this.campuses,
    required this.canChooseCampus,
    required this.onCampus,
    required this.onRefresh,
  });

  @override
  Widget build(BuildContext context) {
    final search = TextField(
      controller: controller,
      decoration: InputDecoration(
        hintText: 'Search position or staff member...',
        prefixIcon: const Icon(Icons.search_rounded, size: 20),
        suffixIcon: controller.text.isEmpty ? null : IconButton(onPressed: controller.clear, icon: const Icon(Icons.close_rounded, size: 18)),
        filled: true,
        fillColor: _surface,
        isDense: true,
        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: _gold, width: 1.4)),
      ),
    );

    final campusField = DropdownButtonFormField<String>(
      value: campuses.contains(campus) ? campus : (campuses.isNotEmpty ? campuses.first : null),
      isExpanded: true,
      decoration: InputDecoration(
        prefixIcon: const Icon(Icons.location_on_outlined, size: 19, color: _green),
        filled: true,
        fillColor: _surface,
        isDense: true,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _border)),
      ),
      items: campuses.map((c) => DropdownMenuItem(value: c, child: Text(c, overflow: TextOverflow.ellipsis))).toList(),
      onChanged: canChooseCampus ? onCampus : null,
    );

    return Container(
      padding: EdgeInsets.all(compact ? 13 : 15),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(15), border: Border.all(color: _border)),
      child: compact
          ? Column(children: [search, const SizedBox(height: 10), Row(children: [Expanded(child: campusField), IconButton(onPressed: onRefresh, tooltip: 'Refresh', icon: const Icon(Icons.refresh_rounded, color: _green))])])
          : Row(children: [Expanded(flex: 2, child: search), const SizedBox(width: 10), Expanded(child: campusField), const SizedBox(width: 4), IconButton(onPressed: onRefresh, tooltip: 'Refresh', icon: const Icon(Icons.refresh_rounded, color: _green))]),
    );
  }
}

class _PositionHolderCard extends StatelessWidget {
  final Map<String, dynamic> data;
  final bool compact;
  final bool canManage;
  final VoidCallback onAssign;
  final VoidCallback onRemove;

  const _PositionHolderCard({
    required this.data,
    required this.compact,
    required this.canManage,
    required this.onAssign,
    required this.onRemove,
  });

  @override
  Widget build(BuildContext context) {
    final assigned = data['user_id'] != null;
    final title = '${data['position_title'] ?? 'Position'}';
    final holder = '${data['holder_name'] ?? ''}'.trim();
    final email = '${data['holder_email'] ?? ''}'.trim();
    final role = '${data['holder_role'] ?? ''}'.trim();
    final campus = '${data['routing_campus'] ?? data['campus'] ?? ''}'.trim();
    final scope = '${data['scope_label'] ?? ''}'.trim();

    final details = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 14)),
        const SizedBox(height: 5),
        if (assigned)
          Text(holder.isEmpty ? email : holder, style: const TextStyle(color: _green, fontSize: 12.5, fontWeight: FontWeight.w800))
        else
          Text('No office holder assigned', style: TextStyle(color: Colors.red.shade700, fontSize: 12, fontWeight: FontWeight.w800)),
        if (assigned && email.isNotEmpty) ...[const SizedBox(height: 2), Text(email, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 10.8))],
        const SizedBox(height: 8),
        Wrap(
          spacing: 6,
          runSpacing: 6,
          children: [
            _miniTag(Icons.location_on_outlined, campus.isEmpty ? 'Campus' : campus),
            if (scope.isNotEmpty) _miniTag(scope == 'HEAD QUARTERS' ? Icons.account_balance_rounded : Icons.apartment_rounded, scope),
            if (role.isNotEmpty) _miniTag(Icons.person_outline_rounded, role),
            _miniTag(assigned ? Icons.notifications_active_outlined : Icons.notifications_off_outlined, assigned ? 'Receives routing alerts' : 'Routing disabled'),
          ],
        ),
      ],
    );

    final actions = canManage
        ? Wrap(
            spacing: 7,
            runSpacing: 7,
            children: [
              OutlinedButton.icon(
                onPressed: onAssign,
                style: OutlinedButton.styleFrom(foregroundColor: _green, side: const BorderSide(color: _border), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))),
                icon: Icon(assigned ? Icons.swap_horiz_rounded : Icons.person_add_alt_1_rounded, size: 16),
                label: Text(assigned ? 'CHANGE HOLDER' : 'ASSIGN HOLDER', style: const TextStyle(fontSize: 9.5, fontWeight: FontWeight.w900)),
              ),
              if (assigned)
                IconButton(onPressed: onRemove, tooltip: 'Remove holder', icon: Icon(Icons.person_remove_outlined, color: Colors.red.shade700, size: 20)),
            ],
          )
        : null;

    return Container(
      padding: EdgeInsets.all(compact ? 14 : 16),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(14), border: Border.all(color: assigned ? _border : Colors.red.shade100)),
      child: compact
          ? Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Row(crossAxisAlignment: CrossAxisAlignment.start, children: [_statusIcon(assigned), const SizedBox(width: 12), Expanded(child: details)]), if (actions != null) ...[const SizedBox(height: 12), actions]])
          : Row(children: [_statusIcon(assigned), const SizedBox(width: 14), Expanded(child: details), if (actions != null) ...[const SizedBox(width: 14), actions]]),
    );
  }

  Widget _statusIcon(bool assigned) => Container(
        width: 46,
        height: 46,
        decoration: BoxDecoration(color: (assigned ? _green : Colors.red).withOpacity(0.07), borderRadius: BorderRadius.circular(13)),
        child: Icon(assigned ? Icons.badge_rounded : Icons.warning_amber_rounded, color: assigned ? _green : Colors.red.shade700, size: 23),
      );

  Widget _miniTag(IconData icon, String text) => Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
        decoration: BoxDecoration(color: _surface, borderRadius: BorderRadius.circular(20)),
        child: Row(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 12, color: _muted), const SizedBox(width: 4), Text(text, style: const TextStyle(color: _muted, fontSize: 9.5, fontWeight: FontWeight.w700))]),
      );
}

class _AssignHolderDialog extends StatefulWidget {
  final String campus;
  final String position;
  final int? currentUserId;
  final List<Map<String, dynamic>> users;

  const _AssignHolderDialog({
    required this.campus,
    required this.position,
    required this.currentUserId,
    required this.users,
  });

  @override
  State<_AssignHolderDialog> createState() => _AssignHolderDialogState();
}

class _AssignHolderDialogState extends State<_AssignHolderDialog> {
  final _search = TextEditingController();
  int? _selected;

  @override
  void initState() {
    super.initState();
    _selected = widget.currentUserId;
    _search.addListener(() => setState(() {}));
  }

  @override
  void dispose() {
    _search.dispose();
    super.dispose();
  }

  List<Map<String, dynamic>> get _filtered {
    final q = _search.text.trim().toLowerCase();
    if (q.isEmpty) return widget.users;
    return widget.users.where((u) {
      final text = '${u['full_name'] ?? ''} ${u['email'] ?? ''} ${u['role'] ?? ''} ${u['position'] ?? ''} ${u['school'] ?? ''} ${u['program'] ?? ''}'.toLowerCase();
      return text.contains(q);
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    return Dialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 16),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 620, maxHeight: size.height * 0.82),
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.fromLTRB(18, 16, 10, 16),
              decoration: const BoxDecoration(color: _green, borderRadius: BorderRadius.vertical(top: Radius.circular(18)), border: Border(bottom: BorderSide(color: _gold, width: 3))),
              child: Row(children: [const Icon(Icons.manage_accounts_rounded, color: Colors.white), const SizedBox(width: 10), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [const Text('ASSIGN ROUTING HOLDER', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 14, letterSpacing: 0.6)), const SizedBox(height: 2), Text('${widget.position} • ${widget.campus}', maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: Color(0xFFE1EFE7), fontSize: 10.5))])), IconButton(onPressed: () => Navigator.pop(context), icon: const Icon(Icons.close_rounded, color: Colors.white))]),
            ),
            Padding(
              padding: const EdgeInsets.all(14),
              child: TextField(
                controller: _search,
                autofocus: false,
                decoration: InputDecoration(hintText: 'Search administrators holding this position...', prefixIcon: const Icon(Icons.search_rounded), filled: true, fillColor: _surface, isDense: true, border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _border))),
              ),
            ),
            Expanded(
              child: ListView.separated(
                padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
                itemCount: _filtered.length,
                separatorBuilder: (_, __) => const SizedBox(height: 7),
                itemBuilder: (context, index) {
                  final user = _filtered[index];
                  final id = int.tryParse('${user['id'] ?? 0}') ?? 0;
                  final selected = id == _selected;
                  final name = '${user['full_name'] ?? user['email'] ?? 'Staff'}';
                  final subtitle = ['${user['position'] ?? user['role'] ?? ''}', '${user['school'] ?? ''}', '${user['program'] ?? ''}'].where((e) => e.trim().isNotEmpty && e != 'null').join(' • ');
                  return Material(
                    color: selected ? _green.withOpacity(0.07) : Colors.white,
                    borderRadius: BorderRadius.circular(12),
                    child: InkWell(
                      borderRadius: BorderRadius.circular(12),
                      onTap: () => setState(() => _selected = id),
                      child: Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), border: Border.all(color: selected ? _green.withOpacity(0.35) : _border)),
                        child: Row(children: [CircleAvatar(radius: 20, backgroundColor: _green.withOpacity(0.08), child: Text(_initials(name), style: const TextStyle(color: _green, fontWeight: FontWeight.w900, fontSize: 11))), const SizedBox(width: 11), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(name, style: const TextStyle(color: _ink, fontWeight: FontWeight.w800, fontSize: 12.5)), if (subtitle.isNotEmpty) ...[const SizedBox(height: 2), Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 10.5))]])), Radio<int>(value: id, groupValue: _selected, activeColor: _green, onChanged: (value) => setState(() => _selected = value))]),
                      ),
                    ),
                  );
                },
              ),
            ),
            Container(
              padding: const EdgeInsets.all(14),
              decoration: const BoxDecoration(border: Border(top: BorderSide(color: _border))),
              child: Row(children: [Expanded(child: Text('Only administrators whose database position matches this office can be assigned. The selected account will receive action-required notifications.', style: const TextStyle(color: _muted, fontSize: 10.5, height: 1.35))), const SizedBox(width: 10), FilledButton.icon(onPressed: _selected == null ? null : () => Navigator.pop(context, _selected), style: FilledButton.styleFrom(backgroundColor: _green, foregroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))), icon: const Icon(Icons.verified_user_outlined, size: 17), label: const Text('ASSIGN', style: TextStyle(fontSize: 10, fontWeight: FontWeight.w900)))]),
            ),
          ],
        ),
      ),
    );
  }

  String _initials(String name) {
    final parts = name.trim().split(RegExp(r'\s+')).where((e) => e.isNotEmpty).toList();
    if (parts.isEmpty) return '?';
    if (parts.length == 1) return parts.first.substring(0, 1).toUpperCase();
    return '${parts.first.substring(0, 1)}${parts.last.substring(0, 1)}'.toUpperCase();
  }
}

class _DirectoryEmpty extends StatelessWidget {
  const _DirectoryEmpty();
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 52),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16), border: Border.all(color: _border)),
      child: const Column(children: [Icon(Icons.badge_outlined, color: _green, size: 46), SizedBox(height: 12), Text('Required workflow positions are missing', style: TextStyle(color: _ink, fontSize: 16, fontWeight: FontWeight.w900)), SizedBox(height: 5), Text('A Registrar is required for each campus. DVC1, Accountant, CFO and CEO are required once under Head Quarters. The routing directory resolves the campus Registrar first and then the central approval offices.', textAlign: TextAlign.center, style: TextStyle(color: _muted, fontSize: 11.5))]),
    );
  }
}

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: Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisSize: MainAxisSize.min, children: [Icon(Icons.cloud_off_rounded, size: 48, color: Colors.red.shade300), const SizedBox(height: 12), Text(message, textAlign: TextAlign.center, style: const TextStyle(color: _muted)), const SizedBox(height: 14), OutlinedButton.icon(onPressed: onRetry, icon: const Icon(Icons.refresh_rounded), label: const Text('Retry'))])));
  }
}
