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

class MarketingTrendChart extends StatelessWidget {
  const MarketingTrendChart({super.key, required this.rows});
  final List<Map<String, dynamic>> rows;
  @override
  Widget build(BuildContext context) {
    if (rows.isEmpty) return const MarketingEmptyState(text: 'Monthly performance records will build the trend chart.');
    final total = rows.fold<int>(0, (sum, row) => sum + marketingNumber(row['students_enrolled']));
    return Container(padding: const EdgeInsets.all(16), decoration: BoxDecoration(color: Colors.white, border: Border.all(color: marketingLine)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        Row(children: [const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Monthly enrollment trend', style: TextStyle(color: marketingInk,fontWeight: FontWeight.w800,fontSize:15)), SizedBox(height:3), Text('Recorded student enrollments by month',style:TextStyle(color:marketingMuted,fontSize:12))])), Container(padding:const EdgeInsets.symmetric(horizontal:10,vertical:7),color:const Color(0xFFEAF3EE),child:Text('$total enrolled',style:const TextStyle(color:marketingGreen,fontWeight:FontWeight.w800,fontSize:12)))]),
        const SizedBox(height:12), Expanded(child: CustomPaint(painter:_TrendPainter(rows),child:const SizedBox.expand())),
        Row(children:[Container(width:9,height:9,color:marketingGreen),const SizedBox(width:6),const Text('Students enrolled',style:TextStyle(color:marketingMuted,fontSize:11)),const Spacer(),Text('${rows.last['label']??''}',style:const TextStyle(color:marketingMuted,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, 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)=>marketingNumber(r['students_enrolled']).toDouble()).toList(); final maximum=values.fold<double>(1,(a,b)=>a>b?a:b);
    final grid=Paint()..color=marketingLine..strokeWidth=1; const style=TextStyle(color:marketingMuted,fontSize:9);
    for(var i=0;i<=4;i++){final f=i/4,y=plot.bottom-plot.height*f;canvas.drawLine(Offset(plot.left,y),Offset(plot.right,y),grid);final p=TextPainter(text:TextSpan(text:(maximum*f).round().toString(),style:style),textDirection:TextDirection.ltr)..layout(maxWidth:left-7);p.paint(canvas,Offset(0,y-p.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.isEmpty)return;final path=Path()..moveTo(points.first.dx,points.first.dy);for(final p in points.skip(1)){path.lineTo(p.dx,p.dy);}final fill=Path.from(path)..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:[marketingGreen.withOpacity(.2),marketingGreen.withOpacity(.01)]).createShader(plot));canvas.drawPath(path,Paint()..color=marketingGreen..strokeWidth=2.5..style=PaintingStyle.stroke..strokeCap=StrokeCap.round..strokeJoin=StrokeJoin.round);for(final p in points){canvas.drawCircle(p,4,Paint()..color=Colors.white);canvas.drawCircle(p,3,Paint()..color=marketingGreen);}
    for(final i in <int>{0,values.length~/2,values.length-1}){final p=TextPainter(text:TextSpan(text:'${rows[i]['label']??''}',style:style),textDirection:TextDirection.ltr,maxLines:1,ellipsis:'…')..layout(maxWidth:90);final x=(points[i].dx-p.width/2).clamp(plot.left,plot.right-p.width);p.paint(canvas,Offset(x.toDouble(),plot.bottom+7));}
  }
  @override bool shouldRepaint(covariant _TrendPainter old)=>old.rows!=rows;
}
