import 'package:flutter/material.dart';

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

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

class PerformanceDashboardSubTab extends StatefulWidget {
  final bool isAdmin;
  final List<HodAssignment> assignments;
  final Map<String, dynamic> currentUser;

  const PerformanceDashboardSubTab({
    super.key,
    required this.isAdmin,
    required this.assignments,
    required this.currentUser,
  });

  @override
  State<PerformanceDashboardSubTab> createState() => _PerformanceDashboardSubTabState();
}

class _PerformanceDashboardSubTabState extends State<PerformanceDashboardSubTab> {
  PerformancePage? _page;
  List<Map<String, dynamic>> _departments = const [];
  List<Map<String, dynamic>> _campuses = const [];
  bool _loading = true;
  String? _error;
  String _campus = '';
  int? _departmentId;
  final TextEditingController _year = TextEditingController();

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

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

  Future<void> _load() async {
    if (!widget.isAdmin && widget.assignments.isEmpty) {
      if (mounted) setState(() => _loading = false);
      return;
    }
    if (mounted) setState(() { _loading = true; _error = null; });
    try {
      final futures = <Future<dynamic>>[
        StudentPerformanceService.getPerformance(
          campus: _campus,
          departmentId: _departmentId,
          academicYear: _year.text.trim(),
        ),
      ];
      if (widget.isAdmin && _departments.isEmpty) {
        futures.add(StudentPerformanceService.getDepartments());
        futures.add(StudentPerformanceService.getCampuses());
      }
      final results = await Future.wait<dynamic>(futures);
      if (!mounted) return;
      setState(() {
        _page = results[0] as PerformancePage;
        if (results.length > 1) {
          _departments = List<Map<String, dynamic>>.from(results[1] as List);
          _campuses = List<Map<String, dynamic>>.from(results[2] as List);
        }
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() { _loading = false; _error = e.toString().replaceFirst('Exception: ', ''); });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!widget.isAdmin && widget.assignments.isEmpty) return _notHod();
    return LayoutBuilder(builder: (context, constraints) {
      final compact = constraints.maxWidth < 760;
      return RefreshIndicator(
        onRefresh: _load,
        color: _green,
        child: ListView(
          padding: EdgeInsets.fromLTRB(compact ? 12 : 24, 18, compact ? 12 : 24, 80),
          children: [
            _title(compact),
            if (widget.isAdmin) ...[
              const SizedBox(height: 14),
              _filters(compact),
            ],
            const SizedBox(height: 16),
            if (_loading)
              const Padding(padding: EdgeInsets.symmetric(vertical: 110), child: Center(child: CircularProgressIndicator(color: _green)))
            else if (_error != null)
              _message(Icons.cloud_off_rounded, 'Unable to load performance', _error!, action: _load)
            else ...[
              _summary(compact),
              const SizedBox(height: 18),
              if ((_page?.records ?? const []).isEmpty)
                _message(Icons.bar_chart_rounded, 'No promotion examination data', 'No HOD performance submission matches the selected filters.')
              else
                ..._groupedRecords(compact),
            ],
          ],
        ),
      );
    });
  }

  Widget _title(bool compact) {
    return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text(widget.isAdmin ? 'University Performance Overview' : 'Department Performance Overview',
          style: TextStyle(fontSize: compact ? 19 : 23, fontWeight: FontWeight.w900, color: _ink)),
        const SizedBox(height: 5),
        Text(
          widget.isAdmin
              ? 'Compare promotion examination outcomes across campuses and departments.'
              : 'Review promotion examination records submitted for your HOD assignment.',
          style: const TextStyle(color: _muted, fontSize: 12.5, height: 1.4),
        ),
      ])),
      IconButton(tooltip: 'Refresh', onPressed: _load, icon: const Icon(Icons.refresh_rounded, color: _green)),
    ]);
  }

  Widget _filters(bool compact) {
    final campusNames = _campuses.map(_name).where((e) => e.isNotEmpty).toSet().toList()..sort();
    final departments = [..._departments]..sort((a, b) => _name(a).compareTo(_name(b)));
    final widgets = <Widget>[
      DropdownButtonFormField<String>(
        value: _campus,
        isExpanded: true,
        decoration: _decor('Campus', Icons.apartment_rounded),
        items: [const DropdownMenuItem(value: '', child: Text('All campuses')), ...campusNames.map((c) => DropdownMenuItem(value: c, child: Text(c)))],
        onChanged: (value) => setState(() => _campus = value ?? ''),
      ),
      DropdownButtonFormField<int?>(
        value: _departmentId,
        isExpanded: true,
        decoration: _decor('Department', Icons.account_tree_outlined),
        items: [const DropdownMenuItem<int?>(value: null, child: Text('All departments')), ...departments.map((d) => DropdownMenuItem<int?>(value: _id(d), child: Text(_name(d))))],
        onChanged: (value) => setState(() => _departmentId = value),
      ),
      TextField(
        controller: _year,
        keyboardType: TextInputType.number,
        decoration: _decor('Academic Year', Icons.calendar_today_outlined).copyWith(hintText: 'e.g. 2026'),
        onSubmitted: (_) => _load(),
      ),
      FilledButton.icon(
        onPressed: _load,
        icon: const Icon(Icons.filter_alt_rounded),
        label: const Text('Apply'),
        style: FilledButton.styleFrom(backgroundColor: _green, minimumSize: const Size(120, 50), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
      ),
    ];
    if (compact) {
      return Column(children: widgets.map((w) => Padding(padding: const EdgeInsets.only(bottom: 10), child: SizedBox(width: double.infinity, child: w))).toList());
    }
    return Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
      Expanded(child: widgets[0]), const SizedBox(width: 10),
      Expanded(child: widgets[1]), const SizedBox(width: 10),
      SizedBox(width: 160, child: widgets[2]), const SizedBox(width: 10), widgets[3],
    ]);
  }

  Widget _summary(bool compact) {
    final s = _page?.summary ?? PerformanceSummary.empty;
    final cards = [
      _Metric('Students Sat', '${s.sat}', Icons.groups_rounded, _green),
      _Metric('Students Passed', '${s.passed}', Icons.verified_rounded, const Color(0xFF15803D)),
      _Metric('Not Promoted', '${s.failed}', Icons.person_off_outlined, const Color(0xFFB45309)),
      _Metric('Pass Rate', '${s.passRate.toStringAsFixed(1)}%', Icons.trending_up_rounded, _gold),
    ];
    if (compact) {
      return GridView.builder(
        shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: cards.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, crossAxisSpacing: 9, mainAxisSpacing: 9, mainAxisExtent: 112),
        itemBuilder: (_, i) => cards[i],
      );
    }
    return Row(children: List.generate(cards.length, (i) => Expanded(child: Padding(padding: EdgeInsets.only(right: i == cards.length - 1 ? 0 : 12), child: cards[i]))));
  }

  List<Widget> _groupedRecords(bool compact) {
    final records = _page?.records ?? const <PromotionPerformanceRecord>[];
    final groups = <String, List<PromotionPerformanceRecord>>{};
    for (final r in records) {
      final key = widget.isAdmin ? '${r.campus}|||${r.departmentName}' : r.departmentName;
      groups.putIfAbsent(key, () => []).add(r);
    }
    return groups.entries.map((entry) {
      final parts = entry.key.split('|||');
      final title = parts.last;
      final campus = parts.length > 1 ? parts.first : entry.value.first.campus;
      return Padding(
        padding: const EdgeInsets.only(bottom: 16),
        child: Container(
          decoration: BoxDecoration(color: Colors.white, border: Border.all(color: _border), borderRadius: BorderRadius.circular(16)),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Padding(
              padding: const EdgeInsets.all(16),
              child: Row(children: [
                Container(width: 40, height: 40, alignment: Alignment.center, decoration: BoxDecoration(color: _green.withOpacity(.08), borderRadius: BorderRadius.circular(12)), child: const Icon(Icons.account_tree_rounded, color: _green)),
                const SizedBox(width: 11),
                Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  Text(title, style: const TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 15.5)),
                  const SizedBox(height: 2),
                  Text(campus, style: const TextStyle(color: _muted, fontSize: 11)),
                ])),
                Text('${entry.value.length} record${entry.value.length == 1 ? '' : 's'}', style: const TextStyle(color: _muted, fontSize: 10.5, fontWeight: FontWeight.w700)),
              ]),
            ),
            const Divider(height: 1, color: _border),
            ...entry.value.map((r) => _recordRow(r, compact)),
          ]),
        ),
      );
    }).toList();
  }

  Widget _recordRow(PromotionPerformanceRecord r, bool compact) {
    final rate = r.passRate;
    final color = rate >= 70 ? const Color(0xFF15803D) : rate >= 50 ? const Color(0xFFB45309) : Colors.red.shade700;
    if (compact) {
      return Padding(
        padding: const EdgeInsets.all(14),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Row(children: [Expanded(child: Text('${r.academicYear} • ${r.examSession}', style: const TextStyle(fontWeight: FontWeight.w800, color: _ink))), _rateBadge(rate, color)]),
          const SizedBox(height: 6),
          Text(r.levelName, style: const TextStyle(color: _muted, fontSize: 11.5)),
          const SizedBox(height: 10),
          Wrap(spacing: 12, runSpacing: 6, children: [
            _tiny('Sat', r.satCount), _tiny('Passed', r.passedCount), _tiny('Not promoted', r.failedCount),
          ]),
          const SizedBox(height: 7),
          Text('Submitted by ${r.submittedByName}', style: const TextStyle(color: _muted, fontSize: 10.5)),
          const Divider(height: 24, color: _border),
        ]),
      );
    }
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13),
      decoration: const BoxDecoration(border: Border(bottom: BorderSide(color: Color(0xFFEEF1EF)))),
      child: Row(children: [
        Expanded(flex: 2, child: Text('${r.academicYear} • ${r.examSession}', style: const TextStyle(fontWeight: FontWeight.w800, color: _ink, fontSize: 12))),
        Expanded(child: Text(r.levelName, style: const TextStyle(color: _muted, fontSize: 11))),
        SizedBox(width: 76, child: _tiny('Sat', r.satCount)),
        SizedBox(width: 86, child: _tiny('Passed', r.passedCount)),
        SizedBox(width: 96, child: _tiny('Not promoted', r.failedCount)),
        SizedBox(width: 72, child: _rateBadge(rate, color)),
      ]),
    );
  }

  Widget _rateBadge(double value, Color color) => Container(
    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
    decoration: BoxDecoration(color: color.withOpacity(.09), borderRadius: BorderRadius.circular(20)),
    child: Text('${value.toStringAsFixed(1)}%', textAlign: TextAlign.center, style: TextStyle(color: color, fontSize: 10.5, fontWeight: FontWeight.w900)),
  );

  Widget _tiny(String label, int value) => RichText(text: TextSpan(style: const TextStyle(fontSize: 10.5, color: _muted), children: [TextSpan(text: '$label: '), TextSpan(text: '$value', style: const TextStyle(fontWeight: FontWeight.w900, color: _ink))]));

  Widget _notHod() {
    final name = '${widget.currentUser['full_name'] ?? 'Staff Member'}';
    final program = '${widget.currentUser['program'] ?? 'Department not assigned'}';
    final campus = '${widget.currentUser['campus'] ?? 'Campus not assigned'}';
    return Center(
      child: Container(
        width: 600,
        margin: const EdgeInsets.all(18),
        padding: const EdgeInsets.all(28),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20), border: Border.all(color: _border)),
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Container(width: 68, height: 68, decoration: BoxDecoration(color: _gold.withOpacity(.10), shape: BoxShape.circle), child: const Icon(Icons.lock_person_rounded, color: _gold, size: 34)),
          const SizedBox(height: 16),
          const Text('HOD Access Required', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900, color: _ink)),
          const SizedBox(height: 8),
          const Text('Promotion examination performance can only be entered and viewed here by the staff member currently assigned as Head of Department. Administration manages HOD assignments.', textAlign: TextAlign.center, style: TextStyle(color: _muted, height: 1.5)),
          const SizedBox(height: 18),
          _info('Staff member', name), _info('Department', program), _info('Campus', campus),
        ]),
      ),
    );
  }

  Widget _info(String label, String value) => Padding(padding: const EdgeInsets.only(bottom: 7), child: Row(children: [SizedBox(width: 110, child: Text(label, style: const TextStyle(color: _muted, fontSize: 11))), Expanded(child: Text(value, style: const TextStyle(fontWeight: FontWeight.w800, color: _ink, fontSize: 11.5)))]));

  Widget _message(IconData icon, String title, String body, {VoidCallback? action}) => Container(
    padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 52),
    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(18), border: Border.all(color: _border)),
    child: Column(children: [Icon(icon, color: Colors.grey.shade300, size: 52), const SizedBox(height: 12), Text(title, style: const TextStyle(fontSize: 17, fontWeight: FontWeight.w900, color: _ink)), const SizedBox(height: 7), Text(body, textAlign: TextAlign.center, style: const TextStyle(color: _muted)), if (action != null) ...[const SizedBox(height: 14), FilledButton.icon(onPressed: action, icon: const Icon(Icons.refresh), label: const Text('Try again'), style: FilledButton.styleFrom(backgroundColor: _green))]]),
  );

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

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

class _Metric extends StatelessWidget {
  final String label;
  final String value;
  final IconData icon;
  final Color color;
  const _Metric(this.label, this.value, this.icon, this.color);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(color: Colors.white, border: Border.all(color: _border), borderRadius: BorderRadius.circular(15)),
      child: Row(children: [
        Container(width: 42, height: 42, decoration: BoxDecoration(color: color.withOpacity(.09), borderRadius: BorderRadius.circular(12)), child: Icon(icon, color: color, size: 21)),
        const SizedBox(width: 11),
        Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(value, style: const TextStyle(fontSize: 19, fontWeight: FontWeight.w900, color: _ink)), const SizedBox(height: 2), Text(label, style: const TextStyle(fontSize: 10.5, color: _muted, fontWeight: FontWeight.w600))])),
      ]),
    );
  }
}
