import 'package:flutter/material.dart';

import 'marketing_ui.dart';

class MarketingPerformanceChart extends StatelessWidget {
  const MarketingPerformanceChart({super.key, required this.records});
  final List<Map<String, dynamic>> records;

  @override
  Widget build(BuildContext context) {
    final latest = [...records]..sort((a, b) {
      final aPeriod = marketingNumber(a['report_year']) * 12 + marketingNumber(a['report_month']);
      final bPeriod = marketingNumber(b['report_year']) * 12 + marketingNumber(b['report_month']);
      return bPeriod.compareTo(aPeriod);
    });
    final latestPeriod = latest.isEmpty
        ? -1
        : marketingNumber(latest.first['report_year']) * 12 + marketingNumber(latest.first['report_month']);
    final ranked = records.where((row) =>
        marketingNumber(row['report_year']) * 12 + marketingNumber(row['report_month']) == latestPeriod).toList()
      ..sort((a, b) => marketingNumber(b['students_enrolled'])
          .compareTo(marketingNumber(a['students_enrolled'])));
    final visible = ranked.take(8).toList();
    final total = ranked.fold<int>(0, (sum, row) => sum + marketingNumber(row['students_enrolled']));
    final period = ranked.isEmpty
        ? 'Latest recorded period'
        : '${_month(ranked.first['report_month'])} ${ranked.first['report_year']}';
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(color: Colors.white, border: Border.all(color: marketingLine)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        Wrap(
          alignment: WrapAlignment.spaceBetween,
          crossAxisAlignment: WrapCrossAlignment.center,
          spacing: 12,
          runSpacing: 8,
          children: [
            const SizedBox(width: 230, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text('Center enrollment comparison', style: TextStyle(color: marketingInk, fontSize: 15, fontWeight: FontWeight.w900)),
              SizedBox(height: 3),
              Text('Students enrolled against each center’s target', style: TextStyle(color: marketingMuted, fontSize: 12)),
            ])),
            Container(color: const Color(0xFFEAF3EE), padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 7),
              child: Text('$total enrolled • $period', style: const TextStyle(color: marketingGreen, fontSize: 12, fontWeight: FontWeight.w800))),
          ],
        ),
        const SizedBox(height: 14),
        if (visible.isEmpty)
          const SizedBox(height: 150, child: Center(child: Text('Add monthly figures to see center comparisons.', style: TextStyle(color: marketingMuted))))
        else
          SizedBox(height: 245, child: CustomPaint(painter: _CenterBarPainter(visible), child: const SizedBox.expand())),
        const SizedBox(height: 4),
        const Wrap(spacing: 18, runSpacing: 8, children: [
          _Legend(color: marketingGreen, label: 'Enrolled'),
          _Legend(color: Color(0xFFD6B45C), label: 'Target'),
          Text('Showing up to 8 leading centers', style: TextStyle(color: marketingMuted, fontSize: 11)),
        ]),
      ]),
    );
  }

  static String _month(dynamic value) {
    const names = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    final index = int.tryParse('$value') ?? 0;
    return index > 0 && index < names.length ? names[index] : 'Month';
  }
}

class _Legend extends StatelessWidget {
  const _Legend({required this.color, required this.label});
  final Color color;
  final String label;
  @override
  Widget build(BuildContext context) => Row(mainAxisSize: MainAxisSize.min, children: [
    Container(width: 9, height: 9, color: color), const SizedBox(width: 6),
    Text(label, style: const TextStyle(color: marketingMuted, fontSize: 11)),
  ]);
}

class _CenterBarPainter extends CustomPainter {
  _CenterBarPainter(this.rows);
  final List<Map<String, dynamic>> rows;

  @override
  void paint(Canvas canvas, Size size) {
    const left = 40.0, right = 8.0, top = 12.0, bottom = 52.0;
    final plot = Rect.fromLTRB(left, top, size.width - right, size.height - bottom);
    if (plot.width <= 0 || plot.height <= 0) return;
    final maxValue = rows.fold<double>(1, (max, row) {
      final enrolled = marketingNumber(row['students_enrolled']).toDouble();
      final target = marketingNumber(row['enrollment_target']).toDouble();
      return [max, enrolled, target].reduce((a, b) => a > b ? a : b);
    });
    final gridPaint = Paint()..color = marketingLine..strokeWidth = 1;
    const textStyle = TextStyle(color: marketingMuted, fontSize: 9);
    for (var i = 0; i <= 4; i++) {
      final fraction = i / 4;
      final y = plot.bottom - plot.height * fraction;
      canvas.drawLine(Offset(plot.left, y), Offset(plot.right, y), gridPaint);
      final label = TextPainter(text: TextSpan(text: (maxValue * fraction).round().toString(), style: textStyle), textDirection: TextDirection.ltr)
        ..layout(maxWidth: left - 7);
      label.paint(canvas, Offset(0, y - label.height / 2));
    }
    final slot = plot.width / rows.length;
    final barWidth = (slot * .25).clamp(5.0, 20.0).toDouble();
    for (var i = 0; i < rows.length; i++) {
      final row = rows[i];
      final centerX = plot.left + slot * (i + .5);
      final enrolled = marketingNumber(row['students_enrolled']).toDouble();
      final target = marketingNumber(row['enrollment_target']).toDouble();
      final enrolledHeight = plot.height * enrolled / maxValue;
      final targetHeight = plot.height * target / maxValue;
      canvas.drawRect(Rect.fromLTWH(centerX - barWidth - 2, plot.bottom - enrolledHeight, barWidth, enrolledHeight), Paint()..color = marketingGreen);
      canvas.drawRect(Rect.fromLTWH(centerX + 2, plot.bottom - targetHeight, barWidth, targetHeight), Paint()..color = const Color(0xFFD6B45C));
      final name = '${row['center_name'] ?? 'Center'}';
      final painter = TextPainter(text: TextSpan(text: name, style: textStyle), textDirection: TextDirection.ltr, maxLines: 2, ellipsis: '…')
        ..layout(maxWidth: (slot - 2).clamp(28.0, 80.0).toDouble());
      painter.paint(canvas, Offset(centerX - painter.width / 2, plot.bottom + 7));
    }
  }

  @override
  bool shouldRepaint(covariant _CenterBarPainter oldDelegate) => oldDelegate.rows != rows;
}
