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 PromotionEntrySubTab extends StatefulWidget {
  final List<HodAssignment> assignments;
  final Future<void> Function()? onChanged;

  const PromotionEntrySubTab({
    super.key,
    required this.assignments,
    this.onChanged,
  });

  @override
  State<PromotionEntrySubTab> createState() => _PromotionEntrySubTabState();
}

class _PromotionEntrySubTabState extends State<PromotionEntrySubTab> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _year = TextEditingController(text: '${DateTime.now().year}');
  final TextEditingController _session = TextEditingController(text: 'Promotion Examination');
  final TextEditingController _level = TextEditingController();
  final TextEditingController _sat = TextEditingController();
  final TextEditingController _passed = TextEditingController();
  final TextEditingController _notes = TextEditingController();

  HodAssignment? _selected;
  List<PromotionPerformanceRecord> _records = const [];
  bool _loading = true;
  bool _saving = false;
  String? _error;
  PromotionPerformanceRecord? _editing;

  @override
  void initState() {
    super.initState();
    if (widget.assignments.isNotEmpty) _selected = widget.assignments.first;
    _loadRecords();
    _sat.addListener(_rebuildCounts);
    _passed.addListener(_rebuildCounts);
  }

  @override
  void didUpdateWidget(covariant PromotionEntrySubTab oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.assignments.isEmpty) {
      _selected = null;
      return;
    }
    if (_selected == null) {
      _selected = widget.assignments.first;
      return;
    }
    HodAssignment? replacement;
    for (final assignment in widget.assignments) {
      if (assignment.id == _selected!.id) {
        replacement = assignment;
        break;
      }
    }
    _selected = replacement ?? widget.assignments.first;
  }

  @override
  void dispose() {
    _year.dispose(); _session.dispose(); _level.dispose(); _sat.dispose(); _passed.dispose(); _notes.dispose();
    super.dispose();
  }

  void _rebuildCounts() { if (mounted) setState(() {}); }

  int get _satCount => int.tryParse(_sat.text.trim()) ?? 0;
  int get _passedCount => int.tryParse(_passed.text.trim()) ?? 0;
  int get _failedCount => _satCount >= _passedCount ? _satCount - _passedCount : 0;
  double get _rate => _satCount > 0 ? (_passedCount / _satCount) * 100 : 0;

  Future<void> _loadRecords() async {
    if (_selected == null) {
      if (mounted) setState(() => _loading = false);
      return;
    }
    if (mounted) setState(() { _loading = true; _error = null; });
    try {
      final page = await StudentPerformanceService.getPerformance(
        departmentId: _selected!.departmentId,
        campus: _selected!.campus,
      );
      if (!mounted) return;
      setState(() { _records = page.records; _loading = false; });
    } catch (e) {
      if (!mounted) return;
      setState(() { _loading = false; _error = e.toString().replaceFirst('Exception: ', ''); });
    }
  }

  Future<void> _save() async {
    if (_saving || _selected == null || !(_formKey.currentState?.validate() ?? false)) return;
    if (_passedCount > _satCount) {
      _snack('Students passed cannot be greater than students who sat for the examination.', error: true);
      return;
    }
    setState(() => _saving = true);
    try {
      if (_editing == null) {
        await StudentPerformanceService.createPerformance(
          departmentId: _selected!.departmentId,
          academicYear: _year.text.trim(),
          examSession: _session.text.trim(),
          levelName: _level.text.trim(),
          satCount: _satCount,
          passedCount: _passedCount,
          notes: _notes.text.trim(),
        );
        _snack('Promotion examination performance submitted successfully.');
      } else {
        await StudentPerformanceService.updatePerformance(
          _editing!.id,
          academicYear: _year.text.trim(),
          examSession: _session.text.trim(),
          levelName: _level.text.trim(),
          satCount: _satCount,
          passedCount: _passedCount,
          notes: _notes.text.trim(),
        );
        _snack('Performance record updated successfully.');
      }
      _resetForm();
      await _loadRecords();
      if (widget.onChanged != null) await widget.onChanged!();
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  void _edit(PromotionPerformanceRecord record) {
    setState(() {
      _editing = record;
      _year.text = record.academicYear;
      _session.text = record.examSession;
      _level.text = record.levelName;
      _sat.text = '${record.satCount}';
      _passed.text = '${record.passedCount}';
      _notes.text = record.notes;
    });
  }

  Future<void> _delete(PromotionPerformanceRecord record) async {
    final yes = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        title: const Text('Delete performance record?'),
        content: Text('Delete ${record.academicYear} • ${record.examSession} • ${record.levelName}?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          FilledButton(onPressed: () => Navigator.pop(context, true), style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700), child: const Text('Delete')),
        ],
      ),
    );
    if (yes != true) return;
    try {
      await StudentPerformanceService.deletePerformance(record.id);
      if (_editing?.id == record.id) _resetForm();
      await _loadRecords();
      _snack('Performance record deleted.');
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    }
  }

  void _resetForm() {
    setState(() {
      _editing = null;
      _year.text = '${DateTime.now().year}';
      _session.text = 'Promotion Examination';
      _level.clear(); _sat.clear(); _passed.clear(); _notes.clear();
    });
  }

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

  @override
  Widget build(BuildContext context) {
    if (widget.assignments.isEmpty) {
      return const Center(child: Text('No active HOD assignment was found.'));
    }
    return LayoutBuilder(builder: (context, constraints) {
      final compact = constraints.maxWidth < 820;
      return SingleChildScrollView(
        padding: EdgeInsets.fromLTRB(compact ? 12 : 24, 18, compact ? 12 : 24, 80),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(_editing == null ? 'Record Promotion Examination Results' : 'Edit Promotion Examination Record',
            style: TextStyle(fontSize: compact ? 19 : 23, fontWeight: FontWeight.w900, color: _ink)),
          const SizedBox(height: 5),
          const Text('The server accepts submissions only from the active HOD assigned to the selected department.', style: TextStyle(color: _muted, fontSize: 12.5)),
          const SizedBox(height: 16),
          if (compact)
            Column(children: [_formPanel(compact), const SizedBox(height: 16), _previewPanel()])
          else
            Row(crossAxisAlignment: CrossAxisAlignment.start, children: [Expanded(flex: 3, child: _formPanel(compact)), const SizedBox(width: 16), Expanded(flex: 2, child: _previewPanel())]),
          const SizedBox(height: 22),
          _recentHeader(),
          const SizedBox(height: 10),
          if (_loading)
            const Padding(padding: EdgeInsets.all(50), child: Center(child: CircularProgressIndicator(color: _green)))
          else if (_error != null)
            _message(_error!)
          else if (_records.isEmpty)
            _message('No promotion examination records have been submitted for this department yet.')
          else
            ..._records.map((r) => _recordCard(r, compact)),
        ]),
      );
    });
  }

  Widget _formPanel(bool compact) {
    return Container(
      padding: EdgeInsets.all(compact ? 15 : 20),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(18), border: Border.all(color: _border)),
      child: Form(
        key: _formKey,
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          const Text('HOD & Department', style: TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 14)),
          const SizedBox(height: 10),
          DropdownButtonFormField<HodAssignment>(
            value: _selected,
            isExpanded: true,
            decoration: _decor('Department assignment', Icons.account_tree_rounded),
            items: widget.assignments.map((a) => DropdownMenuItem(value: a, child: Text('${a.departmentName} • ${a.campus}', overflow: TextOverflow.ellipsis))).toList(),
            onChanged: _editing != null ? null : (value) async { setState(() => _selected = value); await _loadRecords(); },
          ),
          if (_selected != null) ...[
            const SizedBox(height: 9),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(color: _green.withOpacity(.045), borderRadius: BorderRadius.circular(12), border: Border.all(color: _green.withOpacity(.12))),
              child: Wrap(spacing: 18, runSpacing: 7, children: [
                _meta(Icons.apartment_rounded, _selected!.campus),
                if (_selected!.school.isNotEmpty) _meta(Icons.school_outlined, _selected!.school),
                _meta(Icons.verified_user_outlined, 'Assigned HOD'),
              ]),
            ),
          ],
          const SizedBox(height: 18),
          const Text('Examination Information', style: TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 14)),
          const SizedBox(height: 10),
          if (compact) ...[
            _yearField(), const SizedBox(height: 10), _sessionField(), const SizedBox(height: 10), _levelField(),
          ] else ...[
            Row(children: [Expanded(child: _yearField()), const SizedBox(width: 10), Expanded(flex: 2, child: _sessionField())]),
            const SizedBox(height: 10), _levelField(),
          ],
          const SizedBox(height: 18),
          const Text('Student Counts', style: TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 14)),
          const SizedBox(height: 10),
          Row(children: [
            Expanded(child: TextFormField(controller: _sat, keyboardType: TextInputType.number, decoration: _decor('Students who sat', Icons.groups_rounded), validator: _numberValidator)),
            const SizedBox(width: 10),
            Expanded(child: TextFormField(controller: _passed, keyboardType: TextInputType.number, decoration: _decor('Students who passed', Icons.verified_rounded), validator: _numberValidator)),
          ]),
          const SizedBox(height: 10),
          TextFormField(controller: _notes, minLines: 3, maxLines: 5, maxLength: 1500, decoration: _decor('Notes (optional)', Icons.notes_rounded).copyWith(hintText: 'Add any context management should know.')),
          const SizedBox(height: 4),
          Row(mainAxisAlignment: MainAxisAlignment.end, children: [
            if (_editing != null) TextButton.icon(onPressed: _saving ? null : _resetForm, icon: const Icon(Icons.close), label: const Text('Cancel edit')),
            const SizedBox(width: 8),
            FilledButton.icon(
              onPressed: _saving ? null : _save,
              icon: _saving ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : Icon(_editing == null ? Icons.send_rounded : Icons.save_rounded),
              label: Text(_saving ? 'Saving...' : _editing == null ? 'Submit Results' : 'Save Changes'),
              style: FilledButton.styleFrom(backgroundColor: _green, padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
            ),
          ]),
        ]),
      ),
    );
  }

  Widget _previewPanel() {
    final invalid = _passedCount > _satCount;
    return Container(
      padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(color: const Color(0xFF102B20), borderRadius: BorderRadius.circular(18)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(children: [
          Container(width: 42, height: 42, decoration: BoxDecoration(color: Colors.white.withOpacity(.09), borderRadius: BorderRadius.circular(12)), child: const Icon(Icons.assessment_rounded, color: _gold)),
          const SizedBox(width: 10),
          const Expanded(child: Text('Live Result Summary', style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w900))),
        ]),
        const SizedBox(height: 18),
        _previewRow('Students who sat', '$_satCount'),
        _previewRow('Students passed', '$_passedCount'),
        _previewRow('Not promoted', invalid ? '—' : '$_failedCount'),
        const Divider(color: Colors.white24, height: 28),
        Text(invalid ? 'Invalid counts' : '${_rate.toStringAsFixed(1)}%', style: TextStyle(color: invalid ? Colors.redAccent : _gold, fontSize: 34, fontWeight: FontWeight.w900)),
        const SizedBox(height: 3),
        Text(invalid ? 'Passed cannot exceed sat' : 'Promotion pass rate', style: TextStyle(color: Colors.white.withOpacity(.65), fontSize: 11)),
        const SizedBox(height: 18),
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(color: Colors.white.withOpacity(.06), borderRadius: BorderRadius.circular(12)),
          child: const Text('Counts are recorded as aggregate departmental promotion examination results. Individual student marks are not stored in this module.', style: TextStyle(color: Colors.white70, fontSize: 10.8, height: 1.45)),
        ),
      ]),
    );
  }

  Widget _recentHeader() => Row(children: [
    const Expanded(child: Text('Recent Department Submissions', style: TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 16))),
    IconButton(onPressed: _loadRecords, tooltip: 'Refresh', icon: const Icon(Icons.refresh_rounded, color: _green)),
  ]);

  Widget _recordCard(PromotionPerformanceRecord r, bool compact) {
    return Container(
      margin: const EdgeInsets.only(bottom: 10),
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(15), border: Border.all(color: _border)),
      child: compact
          ? Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              _recordTitle(r), const SizedBox(height: 9),
              Wrap(spacing: 14, runSpacing: 7, children: [_stat('Sat', r.satCount), _stat('Passed', r.passedCount), _stat('Not promoted', r.failedCount), _statText('Pass rate', '${r.passRate.toStringAsFixed(1)}%')]),
              const SizedBox(height: 8), _actions(r),
            ])
          : Row(children: [
              Expanded(flex: 3, child: _recordTitle(r)),
              SizedBox(width: 78, child: _stat('Sat', r.satCount)),
              SizedBox(width: 90, child: _stat('Passed', r.passedCount)),
              SizedBox(width: 110, child: _stat('Not promoted', r.failedCount)),
              SizedBox(width: 90, child: _statText('Pass rate', '${r.passRate.toStringAsFixed(1)}%')),
              const SizedBox(width: 8), _actions(r),
            ]),
    );
  }

  Widget _recordTitle(PromotionPerformanceRecord r) => Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
    Text('${r.academicYear} • ${r.examSession}', style: const TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 12.5)),
    const SizedBox(height: 3), Text(r.levelName, style: const TextStyle(color: _muted, fontSize: 11)),
  ]);

  Widget _actions(PromotionPerformanceRecord r) => Row(mainAxisSize: MainAxisSize.min, children: [
    IconButton(tooltip: 'Edit', onPressed: () => _edit(r), icon: const Icon(Icons.edit_outlined, color: _green, size: 20)),
    IconButton(tooltip: 'Delete', onPressed: () => _delete(r), icon: Icon(Icons.delete_outline, color: Colors.red.shade600, size: 20)),
  ]);

  Widget _stat(String label, int value) => _statText(label, '$value');
  Widget _statText(String label, String value) => Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [Text(value, style: const TextStyle(fontWeight: FontWeight.w900, color: _ink, fontSize: 13)), Text(label, style: const TextStyle(color: _muted, fontSize: 9.5))]);
  Widget _meta(IconData icon, String text) => Row(mainAxisSize: MainAxisSize.min, children: [Icon(icon, color: _green, size: 15), const SizedBox(width: 5), Text(text, style: const TextStyle(color: _muted, fontSize: 10.5, fontWeight: FontWeight.w700))]);
  Widget _previewRow(String label, String value) => Padding(padding: const EdgeInsets.only(bottom: 9), child: Row(children: [Expanded(child: Text(label, style: TextStyle(color: Colors.white.withOpacity(.68), fontSize: 11.5))), Text(value, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 14))]));

  Widget _yearField() => TextFormField(controller: _year, keyboardType: TextInputType.number, maxLength: 9, decoration: _decor('Academic year', Icons.calendar_month_rounded).copyWith(counterText: '', hintText: '2026'), validator: (v) => (v ?? '').trim().isEmpty ? 'Required' : null);
  Widget _sessionField() => TextFormField(controller: _session, maxLength: 150, decoration: _decor('Examination session', Icons.event_note_rounded).copyWith(counterText: '', hintText: 'Promotion Examination'), validator: (v) => (v ?? '').trim().isEmpty ? 'Required' : null);
  Widget _levelField() => TextFormField(controller: _level, maxLength: 120, decoration: _decor('Level / cohort', Icons.stairs_rounded).copyWith(counterText: '', hintText: 'e.g. Year 2 to Year 3'), validator: (v) => (v ?? '').trim().isEmpty ? 'Required' : null);
  String? _numberValidator(String? value) {
    final n = int.tryParse((value ?? '').trim());
    if (n == null) return 'Enter a whole number';
    if (n < 0) return 'Cannot be negative';
    return null;
  }

  InputDecoration _decor(String label, IconData icon) => InputDecoration(
    labelText: label, prefixIcon: Icon(icon, color: _green, size: 19), filled: true, fillColor: const Color(0xFFF9FBFA),
    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)),
  );

  Widget _message(String text) => Container(width: double.infinity, padding: const EdgeInsets.all(28), decoration: BoxDecoration(color: Colors.white, border: Border.all(color: _border), borderRadius: BorderRadius.circular(15)), child: Text(text, textAlign: TextAlign.center, style: const TextStyle(color: _muted)));
}
