import 'package:flutter/material.dart';
import '../widgets/ict_ui.dart';

class ICTStudentPerformancePage extends StatefulWidget {
  const ICTStudentPerformancePage({
    super.key,
    required this.programs,
    required this.intakes,
    required this.onSave,
  });

  final List<Map<String, dynamic>> programs;
  final List<Map<String, dynamic>> intakes;
  final Future<void> Function(Map<String, dynamic> record) onSave;

  @override
  State<ICTStudentPerformancePage> createState() => _ICTStudentPerformancePageState();
}

class _ICTStudentPerformancePageState extends State<ICTStudentPerformancePage> {
  int? _programId;
  String? _intakeName;
  int? _intakeYear;
  final _satController = TextEditingController();
  final _passedController = TextEditingController();
  final _failedController = TextEditingController();
  bool _saving = false;

  int get _activeProgramId => _programId ?? (widget.programs.isEmpty ? 0 : ictNumber(widget.programs.first['id']));

  List<Map<String, dynamic>> get _programIntakes => widget.intakes
      .where((row) => ictNumber(row['program_id']) == _activeProgramId)
      .toList();

  List<String> get _intakeNames => _programIntakes
      .map((row) => ictText(row['intake_name'], ''))
      .where((name) => name.isNotEmpty)
      .toSet()
      .toList();

  String? get _activeIntakeName => _intakeName != null && _intakeNames.contains(_intakeName)
      ? _intakeName
      : (_intakeNames.isEmpty ? null : _intakeNames.first);

  List<int> get _intakeYears => _programIntakes
      .where((row) => ictText(row['intake_name'], '') == _activeIntakeName)
      .map((row) => ictNumber(row['intake_year']))
      .toSet()
      .toList()
    ..sort((a, b) => b.compareTo(a));

  int? get _activeIntakeYear => _intakeYear != null && _intakeYears.contains(_intakeYear)
      ? _intakeYear
      : (_intakeYears.isEmpty ? null : _intakeYears.first);

  Map<String, dynamic>? get _selectedIntake {
    for (final row in _programIntakes) {
      if (ictText(row['intake_name'], '') == _activeIntakeName &&
          ictNumber(row['intake_year']) == _activeIntakeYear) return row;
    }
    return null;
  }

  int get _enrolled => ictNumber(_selectedIntake?['total_count']);
  int get _sat => int.tryParse(_satController.text) ?? ictNumber(_selectedIntake?['students_sat']);
  int get _passed => int.tryParse(_passedController.text) ?? ictNumber(_selectedIntake?['students_passed']);
  int get _failed => int.tryParse(_failedController.text) ?? ictNumber(_selectedIntake?['students_failed']);

  @override
  void initState() {
    super.initState();
    _fillSelectedResult();
    _satController.addListener(_refreshChart);
    _passedController.addListener(_refreshChart);
    _failedController.addListener(_refreshChart);
  }

  @override
  void didUpdateWidget(covariant ICTStudentPerformancePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.intakes != widget.intakes || oldWidget.programs != widget.programs) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          _fillSelectedResult();
          setState(() {});
        }
      });
    }
  }

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

  void _fillSelectedResult() {
    final row = _selectedIntake;
    _satController.text = row == null || row['has_performance'] != true ? '' : '${ictNumber(row['students_sat'])}';
    _passedController.text = row == null || row['has_performance'] != true ? '' : '${ictNumber(row['students_passed'])}';
    _failedController.text = row == null || row['has_performance'] != true ? '' : '${ictNumber(row['students_failed'])}';
  }

  @override
  void dispose() {
    _satController.dispose();
    _passedController.dispose();
    _failedController.dispose();
    super.dispose();
  }

  InputDecoration _field(String label, {String? helper}) => InputDecoration(
        labelText: label,
        helperText: helper,
        isDense: true,
        filled: true,
        fillColor: Colors.white,
        border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
        enabledBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: ictLine)),
        focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: ictGreen, width: 1.5)),
      );

  Widget _dropdown<T>({required String label, required T? value, required List<DropdownMenuItem<T>> items, required ValueChanged<T?>? onChanged}) =>
      DropdownButtonFormField<T>(
        value: value,
        isExpanded: true,
        decoration: _field(label),
        items: items,
        onChanged: onChanged,
      );

  Future<void> _save() async {
    final intake = _selectedIntake;
    if (intake == null || _activeIntakeYear == null || _activeIntakeName == null) {
      _message('Choose a program, intake and intake year first.', error: true);
      return;
    }
    final sat = int.tryParse(_satController.text.trim());
    final passed = int.tryParse(_passedController.text.trim());
    final failed = int.tryParse(_failedController.text.trim());
    if (sat == null || passed == null || failed == null || sat < 0 || passed < 0 || failed < 0) {
      _message('Enter valid, non-negative examination counts.', error: true);
      return;
    }
    if (passed + failed != sat) {
      _message('Passed and failed must add up to the number who sat the examination.', error: true);
      return;
    }
    if (sat > _enrolled) {
      _message('The number who sat cannot exceed the intake enrollment of $_enrolled.', error: true);
      return;
    }

    setState(() => _saving = true);
    try {
      await widget.onSave({
        'program_id': _activeProgramId,
        'intake_name': _activeIntakeName,
        'intake_year': _activeIntakeYear,
        'promotion_year': _activeIntakeYear! + 1,
        'students_sat': sat,
        'students_passed': passed,
        'students_failed': failed,
      });
      if (mounted) _message('Results saved for the ${_activeIntakeName!} ${_activeIntakeYear!} intake.');
    } catch (error) {
      if (mounted) _message(error.toString().replaceFirst('Bad state: ', ''), error: true);
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  void _message(String text, {bool error = false}) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(text),
      backgroundColor: error ? const Color(0xFF9F2D27) : ictGreenDark,
      behavior: SnackBarBehavior.floating,
    ));
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.sizeOf(context).width;
    final compact = width < 900;
    final selected = _selectedIntake;
    final hasProgram = widget.programs.isNotEmpty;
    final hasIntake = _programIntakes.isNotEmpty;

    final heading = const ICTPageHeading(
      title: 'Student Performance',
      subtitle: 'Promotion examination results by program and intake cohort',
      icon: Icons.assessment_outlined,
    );

    if (!hasProgram) {
      return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        heading,
        const Expanded(child: ICTEmptyState(text: 'Create an ICT Department program first. Student Performance will use programs and intakes added in this workspace.')),
      ]);
    }

    final form = _entryCard(hasIntake);
    final results = _resultsCard(selected);
    if (compact) {
      return ListView(padding: EdgeInsets.zero, children: [
        heading,
        const SizedBox(height: 13),
        form,
        const SizedBox(height: 12),
        SizedBox(height: 390, child: results),
      ]);
    }

    return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
      heading,
      const SizedBox(height: 13),
      Expanded(child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        SizedBox(width: 355, child: SingleChildScrollView(child: form)),
        const SizedBox(width: 12),
        Expanded(child: results),
      ])),
    ]);
  }

  Widget _entryCard(bool hasIntake) => Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(color: Colors.white, border: Border.all(color: ictLine)),
        child: hasIntake ? Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
          const Text('Promotion examination entry', style: TextStyle(color: ictInk, fontWeight: FontWeight.w900, fontSize: 15)),
          const SizedBox(height: 4),
          const Text('Select a live program intake and record the one-year promotion check.', style: TextStyle(color: ictMuted, fontSize: 12)),
          const SizedBox(height: 15),
          _dropdown<int>(
            label: 'Program',
            value: _activeProgramId,
            items: widget.programs.map((program) => DropdownMenuItem(
              value: ictNumber(program['id']),
              child: Text('${ictText(program['school_name'])} · ${ictText(program['program_name'])}', overflow: TextOverflow.ellipsis),
            )).toList(),
            onChanged: (value) => setState(() { _programId = value; _intakeName = null; _intakeYear = null; _fillSelectedResult(); }),
          ),
          const SizedBox(height: 10),
          _dropdown<String>(
            label: 'Intake',
            value: _activeIntakeName,
            items: _intakeNames.map((name) => DropdownMenuItem(value: name, child: Text(name, overflow: TextOverflow.ellipsis))).toList(),
            onChanged: (value) => setState(() { _intakeName = value; _intakeYear = null; _fillSelectedResult(); }),
          ),
          const SizedBox(height: 10),
          _dropdown<int>(
            label: 'Intake year',
            value: _activeIntakeYear,
            items: _intakeYears.map((year) => DropdownMenuItem(value: year, child: Text('$year'))).toList(),
            onChanged: (value) => setState(() { _intakeYear = value; _fillSelectedResult(); }),
          ),
          const SizedBox(height: 11),
          Container(
            padding: const EdgeInsets.all(11),
            decoration: const BoxDecoration(color: Color(0xFFEAF3EE)),
            child: Row(children: [
              const Icon(Icons.event_available_outlined, size: 19, color: ictGreen),
              const SizedBox(width: 9),
              Expanded(child: Text(
                _activeIntakeYear == null ? 'Promotion examination year: —' : 'Promotion examination year: ${_activeIntakeYear! + 1}',
                style: const TextStyle(color: ictGreenDark, fontWeight: FontWeight.w800, fontSize: 12),
              )),
              Text('Enrolled ${_selectedIntake == null ? '—' : _enrolled}', style: const TextStyle(color: ictMuted, fontSize: 11)),
            ]),
          ),
          const SizedBox(height: 13),
          _numberField(_satController, 'Students who sat'),
          const SizedBox(height: 10),
          Row(children: [
            Expanded(child: _numberField(_passedController, 'Passed')),
            const SizedBox(width: 9),
            Expanded(child: _numberField(_failedController, 'Failed')),
          ]),
          const SizedBox(height: 9),
          const Text('Passed + failed must equal students who sat. Students who did not sit are calculated from the intake total.',
            style: TextStyle(color: ictMuted, fontSize: 11, height: 1.35)),
          const SizedBox(height: 14),
          SizedBox(height: 46, child: ElevatedButton.icon(
            onPressed: _saving ? null : _save,
            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 RESULTS'),
            style: ElevatedButton.styleFrom(backgroundColor: ictGreen, foregroundColor: Colors.white, elevation: 0,
              shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero)),
          )),
        ]) : const ICTEmptyState(text: 'Add an intake enrollment for this program to record its promotion examination results.'),
      );

  Widget _numberField(TextEditingController controller, String label) => TextField(
        controller: controller,
        keyboardType: const TextInputType.numberWithOptions(decimal: false, signed: false),
        decoration: InputDecoration(
          labelText: label,
          isDense: true,
          filled: true,
          fillColor: Colors.white,
          border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
          enabledBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: ictLine)),
          focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: ictGreen, width: 1.5)),
        ),
      );

  Widget _resultsCard(Map<String, dynamic>? selected) {
    final total = selected == null ? 0 : ictNumber(selected['total_count']);
    final hasResult = selected?['has_performance'] == true;
    final sat = hasResult ? ictNumber(selected?['students_sat']) : 0;
    final passed = hasResult ? ictNumber(selected?['students_passed']) : 0;
    final failed = hasResult ? ictNumber(selected?['students_failed']) : 0;
    final notSat = (total - sat).clamp(0, total).toInt();
    final passRate = sat == 0 ? '—' : '${(passed * 100 / sat).toStringAsFixed(1)}%';
    final items = <_BarValue>[
      _BarValue('Passed', passed, ictGreen),
      _BarValue('Failed', failed, const Color(0xFFB54747)),
      _BarValue('Did not sit', notSat, const Color(0xFF3578B8)),
    ];
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(color: Colors.white, border: Border.all(color: ictLine)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        Row(children: [
          const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text('Cohort performance', style: TextStyle(color: ictInk, fontWeight: FontWeight.w900, fontSize: 15)),
            SizedBox(height: 3),
            Text('Promotion examination outcomes for the selected program and intake', style: TextStyle(color: ictMuted, fontSize: 12)),
          ])),
          if (selected != null) Container(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), color: const Color(0xFFEAF3EE),
            child: Text('Pass rate $passRate', style: const TextStyle(color: ictGreen, fontWeight: FontWeight.w800, fontSize: 12))),
        ]),
        const SizedBox(height: 14),
        Wrap(spacing: 8, runSpacing: 8, children: [
          _miniMetric('Enrolled', '$total', ictGreen),
          _miniMetric('Sat', '$sat', ictBlue),
          _miniMetric('Passed', '$passed', ictGreen),
          _miniMetric('Failed', '$failed', const Color(0xFFB54747)),
        ]),
        const SizedBox(height: 12),
        if (!hasResult)
          const Expanded(child: ICTEmptyState(text: 'Save the promotion results to view this cohort’s performance chart.'))
        else ...[
          Expanded(child: CustomPaint(painter: _PerformanceBars(items), child: const SizedBox.expand())),
          const SizedBox(height: 7),
          Text('${ictText(selected?['school_name'])}  /  ${ictText(selected?['program_name'])}  /  ${ictText(selected?['intake_name'])} ${ictText(selected?['intake_year'])}  →  ${ictText(selected?['promotion_year'])}',
            maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: ictMuted, fontSize: 11)),
        ],
      ]),
    );
  }

  Widget _miniMetric(String title, String value, Color color) => Container(
        constraints: const BoxConstraints(minWidth: 92),
        padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 8),
        decoration: BoxDecoration(color: color.withOpacity(.07), border: Border.all(color: color.withOpacity(.16))),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(title, style: const TextStyle(color: ictMuted, fontSize: 10)),
          const SizedBox(height: 2),
          Text(value, style: TextStyle(color: color, fontSize: 17, fontWeight: FontWeight.w900)),
        ]),
      );
}

class _BarValue {
  const _BarValue(this.label, this.value, this.color);
  final String label;
  final int value;
  final Color color;
}

class _PerformanceBars extends CustomPainter {
  const _PerformanceBars(this.values);
  final List<_BarValue> values;

  @override
  void paint(Canvas canvas, Size size) {
    const left = 94.0;
    const right = 44.0;
    const top = 16.0;
    const rowGap = 22.0;
    const barHeight = 23.0;
    final plotWidth = (size.width - left - right).clamp(40.0, double.infinity).toDouble();
    final maxValue = values.fold<int>(1, (max, item) => item.value > max ? item.value : max);
    final labelStyle = const TextStyle(color: ictMuted, fontSize: 12, fontWeight: FontWeight.w600);
    final countStyle = const TextStyle(color: ictInk, fontSize: 11, fontWeight: FontWeight.w800);

    for (var tick = 0; tick <= 4; tick++) {
      final x = left + plotWidth * tick / 4;
      canvas.drawLine(Offset(x, top - 5), Offset(x, size.height - 5), Paint()..color = ictLine..strokeWidth = 1);
      final tp = TextPainter(text: TextSpan(text: '${(maxValue * tick / 4).round()}', style: const TextStyle(color: ictMuted, fontSize: 9)), textDirection: TextDirection.ltr)..layout();
      tp.paint(canvas, Offset(x - tp.width / 2, size.height - tp.height));
    }

    for (var i = 0; i < values.length; i++) {
      final item = values[i];
      final y = top + i * (barHeight + rowGap);
      final label = TextPainter(text: TextSpan(text: item.label, style: labelStyle), textDirection: TextDirection.ltr, maxLines: 1, ellipsis: '…')..layout(maxWidth: left - 10);
      label.paint(canvas, Offset(0, y + (barHeight - label.height) / 2));
      final background = RRect.fromRectAndRadius(Rect.fromLTWH(left, y, plotWidth, barHeight), const Radius.circular(0));
      canvas.drawRRect(background, Paint()..color = const Color(0xFFF2F5F3));
      final width = plotWidth * item.value / maxValue;
      if (width > 0) {
        canvas.drawRect(Rect.fromLTWH(left, y, width, barHeight), Paint()..color = item.color);
      }
      final count = TextPainter(text: TextSpan(text: '${item.value}', style: countStyle), textDirection: TextDirection.ltr)..layout();
      final countX = (left + width + 8).clamp(left + 8, size.width - count.width);
      count.paint(canvas, Offset(countX.toDouble(), y + (barHeight - count.height) / 2));
    }
  }

  @override
  bool shouldRepaint(covariant _PerformanceBars oldDelegate) => oldDelegate.values != values;
}
