import 'package:flutter/material.dart';
import 'business_ui.dart';

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

  @override
  Widget build(BuildContext context) {
    if (rows.isEmpty) {
      return const BusinessEmptyState(text: 'Add intake records to build the enrollment trend.');
    }
    final total = rows.fold<int>(0, (sum, row) => sum + businessNumber(row['total_count']));
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
      decoration: BoxDecoration(color: Colors.white, border: Border.all(color: businessLine)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        Row(children: [
          const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text('Enrollment trend', style: TextStyle(color: businessInk, fontWeight: FontWeight.w800, fontSize: 15)),
            SizedBox(height: 3),
            Text('Students recorded by intake', style: TextStyle(color: businessMuted, fontSize: 12)),
          ])),
          Container(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), color: const Color(0xFFEAF3EE),
            child: Text('$total total', style: const TextStyle(color: businessGreen, fontWeight: FontWeight.w800, fontSize: 12))),
        ]),
        const SizedBox(height: 12),
        Expanded(child: CustomPaint(painter: _TrendPainter(rows), child: const SizedBox.expand())),
        const SizedBox(height: 4),
        Row(children: [
          Container(width: 9, height: 9, color: businessGreen),
          const SizedBox(width: 6),
          const Text('Total enrollment', style: TextStyle(color: businessMuted, fontSize: 11)),
          const Spacer(),
          if (rows.isNotEmpty) Text(businessText(rows.last['label']), style: const TextStyle(color: businessMuted, fontSize: 11)),
        ]),
      ]),
    );
  }
}

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

  @override
  void paint(Canvas canvas, Size size) {
    const left = 42.0, right = 12.0, top = 10.0, bottom = 32.0;
    final plotRight = size.width - right;
    final plotBottom = size.height - bottom;
    final plot = Rect.fromLTRB(left, top, plotRight < left + 1 ? left + 1 : plotRight, plotBottom < top + 1 ? top + 1 : plotBottom);
    final values = rows.map((r) => businessNumber(r['total_count']).toDouble()).toList();
    final maximum = values.fold<double>(1, (a, b) => a > b ? a : b);
    final gridPaint = Paint()..color = businessLine..strokeWidth = 1;
    final labelStyle = const TextStyle(color: businessMuted, 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 = (maximum * fraction).round().toString();
      final painter = TextPainter(text: TextSpan(text: label, style: labelStyle), textDirection: TextDirection.ltr)..layout(maxWidth: left - 7);
      painter.paint(canvas, Offset(0, y - painter.height / 2));
    }

    final points = <Offset>[];
    for (var i = 0; i < values.length; i++) {
      final x = values.length == 1 ? plot.center.dx : plot.left + plot.width * i / (values.length - 1);
      final y = plot.bottom - values[i] / maximum * plot.height;
      points.add(Offset(x, y));
    }

    if (points.isNotEmpty) {
      final line = Path()..moveTo(points.first.dx, points.first.dy);
      for (final point in points.skip(1)) { line.lineTo(point.dx, point.dy); }
      final fill = Path.from(line)
        ..lineTo(points.last.dx, plot.bottom)
        ..lineTo(points.first.dx, plot.bottom)
        ..close();
      canvas.drawPath(fill, Paint()..shader = LinearGradient(
        begin: Alignment.topCenter, end: Alignment.bottomCenter,
        colors: [businessGreen.withOpacity(.20), businessGreen.withOpacity(.01)],
      ).createShader(plot));
      canvas.drawPath(line, Paint()..color = businessGreen..strokeWidth = 2.5..style = PaintingStyle.stroke..strokeCap = StrokeCap.round..strokeJoin = StrokeJoin.round);
      for (final point in points) {
        canvas.drawCircle(point, 4, Paint()..color = Colors.white);
        canvas.drawCircle(point, 3, Paint()..color = businessGreen);
      }

      final labelIndexes = <int>{0, values.length ~/ 2, values.length - 1};
      for (final index in labelIndexes) {
        final text = rows[index]['label']?.toString() ?? '';
        final painter = TextPainter(text: TextSpan(text: text, style: labelStyle), textDirection: TextDirection.ltr, maxLines: 1, ellipsis: '…')..layout(maxWidth: 90);
        final x = (points[index].dx - painter.width / 2).clamp(plot.left, plot.right - painter.width);
        painter.paint(canvas, Offset(x.toDouble(), plot.bottom + 7));
      }
    }
  }

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