// lib/features/admin/tabs/positions/staff_access_control_sub_tab.dart


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

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

// MATCHES EXACTLY WITH _masterModules IN admin_home_screen.dart
const List<String> _systemModules = [
  'University Dashboard',
  //'Manage KPI Dashboard',
  'Library Management',
  'Manage Operations',
  'Request For Leave',
  'Manage Announcements',
  'Manage Uni Events',
  'Help Community Mgt',
  // 'Manage Uni Clubs',
  'Manage Marketplace',
  // 'Manage Accommodation',
  'Employee CVs',
   'My CV',
  'Feed Rockview Assistant',               
  'Help Rockview Assistant',    
  'Student Performance',
  'Manage Uni Requests',
  'Human Resource Mgt',
  // 'Manage Accounts',
  'Manage Uni Asset',
  'Education Department',
  'Business Department',
  'Agriculture Department',
  'Marketing Department',
   'ICT Department',
   'HR Department',
  'Manage IT Support',
  'Uni Announcements',
  'Events Management',
  'Members of Staff',
  'Management News',
  'Need Help? Ask',
  'Clubs Management',
  'Management Market',
  'File Management',
  'Check Assigned Assets',
];

String _staffText(dynamic value, [String fallback = '']) {
  if (value == null) return fallback;
  final text = value.toString().trim();
  return text.isEmpty || text.toLowerCase() == 'null' ? fallback : text;
}
String _staffName(Map<String, dynamic> row) =>
    _staffText(row['full_name'], _staffText(row['name'], 'Unknown'));

class StaffAccessControlSubTab extends StatefulWidget {
  const StaffAccessControlSubTab({super.key});
  @override
  State<StaffAccessControlSubTab> createState() => _StaffAccessControlSubTabState();
}

class _StaffAccessControlSubTabState extends State<StaffAccessControlSubTab> {
  final _horizontal = ScrollController();
  final _vertical = ScrollController();
  final _search = TextEditingController();
  List<Map<String, dynamic>> _staff = [];
  bool _loading = true;
  String? _error;

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

  Future<void> _loadStaff() async {
    if (!mounted) return;
    setState(() { _loading = true; _error = null; });
    try {
      final dynamic result = await ApiClient.getStaff();
      if (result is! List) throw const FormatException('The staff API must return a list.');
      final staff = <Map<String, dynamic>>[];
      for (final item in result) {
        if (item is! Map) throw const FormatException('The staff list contains an invalid record.');
        staff.add(item.map((key, value) => MapEntry(key.toString(), value)));
      }
      if (!mounted) return;
      setState(() { _staff = staff; _loading = false; });
    } catch (error, trace) {
      debugPrint('Staff access control load failed: $error');
      debugPrintStack(stackTrace: trace);
      if (!mounted) return;
      setState(() { _error = error.toString(); _loading = false; });
    }
  }

  Future<void> _manage(Map<String, dynamic> staff) async {
    final result = await showDialog<bool>(
      context: context, barrierDismissible: false,
      builder: (_) => ManageStaffAccessDialog(staffData: staff),
    );
    if (!mounted || result != true) return;
    ScaffoldMessenger.maybeOf(context)?.showSnackBar(const SnackBar(
      content: Text('Staff permissions updated successfully.'), backgroundColor: _darkGreen,
    ));
    await _loadStaff();
  }

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

  @override
  Widget build(BuildContext context) {
    // Explicit light Material prevents dark inherited canvas/text combinations.
    final theme = Theme.of(context);
    return Theme(
      data: theme.copyWith(
        brightness: Brightness.light,
        colorScheme: const ColorScheme.light(primary: _darkGreen, secondary: _standardGold),
        textTheme: theme.textTheme.apply(bodyColor: const Color(0xFF24332B), displayColor: const Color(0xFF24332B)),
      ),
      child: Material(color: const Color(0xFFF7F8FA), child: LayoutBuilder(
        builder: (context, bounds) {
          final viewport = MediaQuery.of(context).size;
          final width = bounds.hasBoundedWidth ? bounds.maxWidth : viewport.width;
          // Expanded below always receives a finite height, including inside a scroll view.
          final height = bounds.hasBoundedHeight ? bounds.maxHeight : viewport.height * 0.8;
          final compact = width < 700;
          final query = _search.text.trim().toLowerCase();
          final rows = _staff.where((row) =>
            _staffName(row).toLowerCase().contains(query) ||
            _staffText(row['email']).toLowerCase().contains(query) ||
            _staffText(row['role']).toLowerCase().contains(query)).toList();
          return SizedBox(width: width, height: height,
            child: Padding(padding: EdgeInsets.all(compact ? 12 : 24),
              child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
                Row(children: [
                  const Expanded(child: Text('Staff access control',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Color(0xFF24332B)))),
                  IconButton(tooltip: 'Refresh staff', onPressed: _loading ? null : _loadStaff,
                    icon: const Icon(Icons.refresh, color: _darkGreen)),
                ]),
                const SizedBox(height: 10),
                TextField(controller: _search, onChanged: (_) => setState(() {}),
                  style: const TextStyle(color: Color(0xFF24332B)),
                  decoration: InputDecoration(
                    isDense: true, filled: true, fillColor: Colors.white,
                    hintText: 'Search name, email or role',
                    hintStyle: const TextStyle(color: Color(0xFF68776E)),
                    prefixIcon: const Icon(Icons.search, color: _darkGreen),
                    suffixIcon: _search.text.isEmpty ? null : IconButton(
                      tooltip: 'Clear search', icon: const Icon(Icons.close),
                      onPressed: () => setState(() => _search.clear())),
                    border: const OutlineInputBorder(borderSide: BorderSide(color: Color(0xFFDCE3DE))),
                  ),
                ),
                const SizedBox(height: 16),
                Expanded(child: Container(
                  decoration: BoxDecoration(color: Colors.white, border: Border.all(color: const Color(0xFFDCE3DE))),
                  child: _loading
                    ? const Center(child: CircularProgressIndicator(color: _darkGreen))
                    : _error != null ? _errorPanel()
                    : rows.isEmpty ? Center(child: Padding(padding: const EdgeInsets.all(24), child: Text(
                        _staff.isEmpty ? 'No staff members found.' : 'No staff match your search.',
                        style: const TextStyle(color: Color(0xFF68776E)))))
                    : LayoutBuilder(builder: (context, tableBounds) => Scrollbar(
                        controller: _vertical,
                        child: SingleChildScrollView(controller: _vertical,
                          child: Scrollbar(controller: _horizontal,
                            notificationPredicate: (notification) => notification.metrics.axis == Axis.horizontal,
                            child: SingleChildScrollView(controller: _horizontal, scrollDirection: Axis.horizontal,
                              child: ConstrainedBox(constraints: BoxConstraints(minWidth: tableBounds.maxWidth),
                                child: DataTable(
                                  headingRowColor: WidgetStateProperty.all(_darkGreen),
                                  headingTextStyle: const TextStyle(color: Colors.white, fontWeight: FontWeight.w700, fontSize: 12),
                                  dataTextStyle: const TextStyle(color: Color(0xFF24332B), fontSize: 13),
                                  horizontalMargin: 20, columnSpacing: 30,
                                  dataRowMinHeight: 58, dataRowMaxHeight: 76,
                                  columns: const [
                                    DataColumn(label: Text('STAFF NAME')), DataColumn(label: Text('EMAIL')),
                                    DataColumn(label: Text('SYSTEM ROLE')), DataColumn(label: Text('PERMISSIONS')),
                                  ],
                                  rows: rows.map((staff) => DataRow(cells: [
                                    DataCell(Text(_staffName(staff))),
                                    DataCell(Text(_staffText(staff['email'], '—'))),
                                    DataCell(Text(_staffText(staff['role'], 'Staff').toUpperCase(),
                                      style: const TextStyle(color: _darkGreen, fontWeight: FontWeight.w600))),
                                    DataCell(OutlinedButton.icon(
                                      onPressed: _staffText(staff['id']).isEmpty ? null : () => _manage(staff),
                                      icon: const Icon(Icons.security_outlined, size: 16),
                                      label: const Text('Manage Access'),
                                      style: OutlinedButton.styleFrom(foregroundColor: _darkGreen),
                                    )),
                                  ])).toList(),
                                ),
                              ),
                            ),
                          ),
                        ),
                      )),
                )),
              ]),
            ),
          );
        },
      )),
    );
  }

  Widget _errorPanel() => SingleChildScrollView(padding: const EdgeInsets.all(24),
    child: Column(children: [
      const Icon(Icons.error_outline, color: Colors.redAccent, size: 30),
      const SizedBox(height: 12),
      const Text('Unable to load staff', style: TextStyle(fontWeight: FontWeight.w700)),
      const SizedBox(height: 8),
      SelectableText(_error ?? '', textAlign: TextAlign.center,
        style: const TextStyle(color: Color(0xFF68776E), fontSize: 12)),
      const SizedBox(height: 12),
      OutlinedButton.icon(onPressed: _loadStaff, icon: const Icon(Icons.refresh), label: const Text('Try again')),
    ]),
  );
}

class ManageStaffAccessDialog extends StatefulWidget {
  final dynamic staffData;
  const ManageStaffAccessDialog({super.key, required this.staffData});
  @override
  State<ManageStaffAccessDialog> createState() => _ManageStaffAccessDialogState();
}

class _ManageStaffAccessDialogState extends State<ManageStaffAccessDialog> {
  bool _saving = false;
  String? _error;
  bool _invalidPermissions = false;
  Map<String, dynamic> _staff = {};
  final Map<String, bool> _access = {for (final module in _systemModules) module: false};
  final Set<String> _otherPermissions = {};

  @override
  void initState() {
    super.initState();
    try {
      final raw = widget.staffData;
      if (raw is! Map) throw const FormatException('Invalid staff record.');
      _staff = raw.map((key, value) => MapEntry(key.toString(), value));
      dynamic permissions = _staff['permissions'];
      if (permissions is String) {
        permissions = permissions.trim().isEmpty ? null : jsonDecode(permissions);
      }
      if (permissions == null) return; // New records retain default-deny.
      if (permissions is! List || permissions.any((item) => item is! String)) {
        throw const FormatException('Permissions must be a JSON list of module names.');
      }
      for (final item in permissions) {
        final module = item as String;
        if (_access.containsKey(module)) {
          _access[module] = true;
        } else {
          // Preserve permissions from modules not represented by this UI.
          _otherPermissions.add(module);
        }
      }
    } catch (error) {
      _invalidPermissions = true;
      _error = 'Existing permissions could not be read. Close and reload before editing. $error';
    }
  }

  Future<void> _savePermissions() async {
    if (_saving || _invalidPermissions) return;
    if (_staffText(_staff['id']).isEmpty) {
      setState(() => _error = 'This staff record has no ID. Reload the staff list.');
      return;
    }
    setState(() { _saving = true; _error = null; });
    final modules = <String>{
      ..._access.entries.where((entry) => entry.value).map((entry) => entry.key),
      ..._otherPermissions,
    }.toList();
    final payload = {
      'full_name': _staff['full_name'] ?? _staff['name'],
      'email': _staff['email'],
      'role': _staff['role'] ?? 'staff',
      'permissions': jsonEncode(modules),
    };
    try {
      final success = await ApiClient.updateStaff(_staff['id'], payload);
      if (!mounted) return;
      if (!success) throw Exception('Server rejected the update.');
      Navigator.of(context).pop(true);
    } catch (error) {
      if (mounted) setState(() => _error = 'Update failed: $error');
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  void _toggleAll(bool value) {
    if (_saving || _invalidPermissions) return;
    setState(() { for (final module in _access.keys) { _access[module] = value; } });
  }

  @override
  Widget build(BuildContext context) {
    final viewport = MediaQuery.of(context).size;
    final enabled = !_saving && !_invalidPermissions;
    return PopScope(canPop: !_saving, child: Dialog(
      backgroundColor: Colors.white,
      insetPadding: const EdgeInsets.all(16),
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      child: SizedBox(
        width: viewport.width > 832 ? 800 : viewport.width - 32,
        height: viewport.height * 0.85,
        child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
          Container(color: _darkGreen, padding: const EdgeInsets.fromLTRB(20, 12, 8, 12),
            child: Row(children: [
              Expanded(child: Text('Access levels: ${_staffName(_staff)}',
                style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w700, fontSize: 16))),
              IconButton(tooltip: 'Close', onPressed: _saving ? null : () => Navigator.of(context).pop(false),
                icon: const Icon(Icons.close, color: Colors.white)),
            ])),
          Expanded(child: SingleChildScrollView(padding: const EdgeInsets.all(20),
            child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
              const Text('Enable or disable dashboard modules for this staff member.',
                style: TextStyle(color: Color(0xFF58675F), fontSize: 13)),
              Wrap(spacing: 8, children: [
                TextButton(onPressed: enabled ? () => _toggleAll(true) : null, child: const Text('ENABLE ALL', style: TextStyle(color: _darkGreen))),
                TextButton(onPressed: enabled ? () => _toggleAll(false) : null, child: const Text('DISABLE ALL', style: TextStyle(color: Colors.redAccent))),
              ]),
              if (_otherPermissions.isNotEmpty) const Padding(
                padding: EdgeInsets.only(bottom: 12), child: Text(
                  'Additional permissions outside this module list are preserved. The bulk controls apply to the modules shown below.',
                  style: TextStyle(color: Color(0xFF58675F), fontSize: 12))),
              if (_error != null) Padding(padding: const EdgeInsets.only(bottom: 14),
                child: SelectableText(_error!, style: const TextStyle(color: Colors.red, fontSize: 13))),
              LayoutBuilder(builder: (context, bounds) {
                final columns = bounds.maxWidth >= 620 ? 2 : 1;
                final width = (bounds.maxWidth - (columns - 1) * 12) / columns;
                return Wrap(spacing: 12, runSpacing: 10, children: _systemModules.map((module) {
                  final selected = _access[module] ?? false;
                  return SizedBox(width: width, child: Container(
                    decoration: BoxDecoration(color: selected ? const Color(0xFFF1F7F3) : Colors.white,
                      border: Border.all(color: const Color(0xFFDCE3DE))),
                    child: SwitchListTile(
                      title: Text(module, style: TextStyle(color: selected ? _darkGreen : const Color(0xFF24332B), fontSize: 13)),
                      value: selected, activeThumbColor: _standardGold, activeTrackColor: _darkGreen,
                      onChanged: enabled ? (value) => setState(() => _access[module] = value) : null,
                    ),
                  ));
                }).toList());
              }),
            ]),
          )),
          Container(padding: const EdgeInsets.all(16),
            decoration: const BoxDecoration(color: Color(0xFFF7F8FA), border: Border(top: BorderSide(color: Color(0xFFDCE3DE)))),
            child: Wrap(alignment: WrapAlignment.end, spacing: 12, runSpacing: 8, children: [
              TextButton(onPressed: _saving ? null : () => Navigator.of(context).pop(false),
                child: const Text('CANCEL', style: TextStyle(color: Color(0xFF58675F)))),
              ElevatedButton.icon(onPressed: enabled ? _savePermissions : null,
                icon: _saving ? const SizedBox(width: 16, height: 16,
                  child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.save_outlined, size: 18),
                label: Text(_saving ? 'SAVING...' : 'SAVE PERMISSIONS'),
                style: ElevatedButton.styleFrom(backgroundColor: _standardGold, foregroundColor: Colors.white)),
            ])),
        ]),
      ),
    ));
  }
}
