import 'package:flutter/material.dart';

import '../widgets/marketing_ui.dart';

import 'marketing_page_common.dart';

class MarketingMonthlyReportsPage extends StatelessWidget {
  const MarketingMonthlyReportsPage({super.key, required this.reports});

  final List<Map<String, dynamic>> reports;

  static const months = [
    '',
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
  ];

  @override
  Widget build(BuildContext context) => MarketingPageFrame(
    title: 'Monthly Reports',

    subtitle:
        'Visual monthly summaries of recruitment, center activity, and target progress',

    icon: Icons.summarize_outlined,

    children: [
      if (reports.isEmpty)
        const MarketingEmptyState(
          text: 'A monthly report will appear after the first month closes.',
        )
      else
        ...reports.map((record) {
          final data = record['report_data'] is Map
              ? Map<String, dynamic>.from(record['report_data'])
              : <String, dynamic>{};

          final summary = data['summary'] is Map
              ? Map<String, dynamic>.from(data['summary'])
              : <String, dynamic>{};

          final centers = marketingMaps(data['centers']);

          final monthNumber = int.tryParse('${record['report_month']}') ?? 0;

          final month = monthNumber > 0 && monthNumber < months.length
              ? months[monthNumber]
              : 'Monthly';

          final year = '${record['report_year'] ?? ''}';

          final enrolled = marketingNumber(summary['students_enrolled']);

          final target = marketingNumber(summary['enrollment_target']);

          final attainment = target == 0
              ? null
              : (100 * enrolled / target).round();

          final top = summary['top_center'] is Map
              ? Map<String, dynamic>.from(summary['top_center'])
              : <String, dynamic>{};

          return Padding(
            padding: const EdgeInsets.only(bottom: 16),

            child: Container(
              clipBehavior: Clip.antiAlias,

              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: marketingLine),
              ),

              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Container(
                    padding: const EdgeInsets.fromLTRB(18, 16, 18, 17),

                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [marketingGreenDark, marketingGreen],
                      ),

                      border: Border(
                        bottom: BorderSide(color: Color(0xFFD6B45C), width: 3),
                      ),
                    ),

                    child: Wrap(
                      alignment: WrapAlignment.spaceBetween,
                      crossAxisAlignment: WrapCrossAlignment.center,
                      spacing: 14,
                      runSpacing: 12,
                      children: [
                        SizedBox(
                          width: 270,
                          child: Row(
                            children: [
                              Container(
                                width: 45,
                                height: 45,
                                color: Colors.white.withOpacity(.12),
                                child: const Icon(
                                  Icons.insert_chart_outlined,
                                  color: Colors.white,
                                  size: 24,
                                ),
                              ),

                              const SizedBox(width: 12),

                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const Text(
                                      'MONTHLY DEPARTMENT REPORT',
                                      style: TextStyle(
                                        color: Color(0xFFDCEBE1),
                                        fontSize: 10,
                                        letterSpacing: 1.1,
                                        fontWeight: FontWeight.w800,
                                      ),
                                    ),

                                    const SizedBox(height: 3),

                                    Text(
                                      '$month $year',
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: const TextStyle(
                                        color: Colors.white,
                                        fontSize: 20,
                                        fontWeight: FontWeight.w900,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),

                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 11,
                            vertical: 8,
                          ),
                          color: Colors.white.withOpacity(.12),

                          child: const Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(
                                Icons.verified_outlined,
                                color: Color(0xFFF3D77B),
                                size: 16,
                              ),
                              SizedBox(width: 7),
                              Text(
                                'SYSTEM GENERATED',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 10,
                                  letterSpacing: .8,
                                  fontWeight: FontWeight.w800,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),

                  Padding(
                    padding: const EdgeInsets.all(16),

                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Wrap(
                          spacing: 9,
                          runSpacing: 9,
                          children: [
                            _ReportMetric(
                              title: 'Students enrolled',
                              value: enrolled,
                              icon: Icons.school_outlined,
                              color: marketingGreen,
                            ),

                            _ReportMetric(
                              title: 'Student inquiries',
                              value: marketingNumber(
                                summary['student_inquiries'],
                              ),
                              icon: Icons.forum_outlined,
                              color: marketingBlue,
                            ),

                            _ReportMetric(
                              title: 'Applications',
                              value: marketingNumber(
                                summary['applications_started'],
                              ),
                              icon: Icons.assignment_outlined,
                              color: const Color(0xFF9B6A13),
                            ),

                            _ReportMetric(
                              title: 'Active centers',
                              value: marketingNumber(summary['center_count']),
                              icon: Icons.storefront_outlined,
                              color: marketingGreenDark,
                            ),
                          ],
                        ),

                        const SizedBox(height: 15),

                        LayoutBuilder(
                          builder: (context, constraints) {
                            final narrow = constraints.maxWidth < 610;

                            final progress = _ReportProgress(
                              enrolled: enrolled,
                              target: target,
                              attainment: attainment,
                            );

                            final highlights = _ReportHighlights(
                              summary: summary,
                              top: top,
                              centers: centers,
                            );

                            if (narrow) {
                              return Column(
                                crossAxisAlignment: CrossAxisAlignment.stretch,
                                children: [
                                  progress,
                                  const SizedBox(height: 12),
                                  highlights,
                                ],
                              );
                            }

                            return Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(width: 245, child: progress),
                                const SizedBox(width: 12),
                                Expanded(child: highlights),
                              ],
                            );
                          },
                        ),

                        if (marketingNumber(summary['outreach_activities']) >
                            0) ...[
                          const SizedBox(height: 12),

                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 13,
                              vertical: 11,
                            ),
                            color: const Color(0xFFF5F7F6),

                            child: Row(
                              children: [
                                const Icon(
                                  Icons.campaign_outlined,
                                  color: marketingGreen,
                                  size: 18,
                                ),
                                const SizedBox(width: 8),

                                Expanded(
                                  child: Text(
                                    '${marketingNumber(summary['outreach_activities'])} outreach activities recorded during $month',
                                    style: const TextStyle(
                                      color: marketingInk,
                                      fontWeight: FontWeight.w700,
                                      fontSize: 12,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        }),
    ],
  );
}

class _ReportMetric extends StatelessWidget {
  const _ReportMetric({
    required this.title,
    required this.value,
    required this.icon,
    required this.color,
  });

  final String title;

  final int value;

  final IconData icon;

  final Color color;

  @override
  Widget build(BuildContext context) => Container(
    constraints: const BoxConstraints(minWidth: 148),

    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11),

    decoration: BoxDecoration(
      color: Colors.white,
      border: Border.all(color: marketingLine),
    ),

    child: Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 34,
          height: 34,
          color: color.withOpacity(.09),
          child: Icon(icon, color: color, size: 18),
        ),

        const SizedBox(width: 9),

        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '$value',
              style: TextStyle(
                color: color,
                fontSize: 18,
                fontWeight: FontWeight.w900,
              ),
            ),

            Text(
              title,
              style: const TextStyle(color: marketingMuted, fontSize: 10),
            ),
          ],
        ),
      ],
    ),
  );
}

class _ReportProgress extends StatelessWidget {
  const _ReportProgress({
    required this.enrolled,
    required this.target,
    required this.attainment,
  });

  final int enrolled, target;

  final int? attainment;

  @override
  Widget build(BuildContext context) => Container(
    padding: const EdgeInsets.all(15),

    decoration: BoxDecoration(
      color: marketingCanvas,
      border: Border.all(color: marketingLine),
    ),

    child: Column(
      children: [
        const Align(
          alignment: Alignment.centerLeft,
          child: Text(
            'TARGET ATTAINMENT',
            style: TextStyle(
              color: marketingMuted,
              fontSize: 10,
              letterSpacing: .9,
              fontWeight: FontWeight.w800,
            ),
          ),
        ),

        const SizedBox(height: 9),

        SizedBox(
          width: 132,
          height: 132,
          child: CustomPaint(
            painter: _DonutPainter(attainment: attainment),
            child: Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    attainment == null ? '—' : '$attainment%',
                    style: const TextStyle(
                      color: marketingGreen,
                      fontSize: 23,
                      fontWeight: FontWeight.w900,
                    ),
                  ),

                  const Text(
                    'achieved',
                    style: TextStyle(color: marketingMuted, fontSize: 10),
                  ),
                ],
              ),
            ),
          ),
        ),

        const SizedBox(height: 8),

        Text(
          target == 0
              ? '$enrolled students enrolled • no target set'
              : '$enrolled of $target students',
          textAlign: TextAlign.center,
          style: const TextStyle(
            color: marketingInk,
            fontSize: 11,
            fontWeight: FontWeight.w700,
          ),
        ),

        if (attainment != null) ...[
          const SizedBox(height: 9),

          ClipRect(
            child: LinearProgressIndicator(
              value: (attainment! / 100).clamp(0.0, 1.0),
              minHeight: 5,
              backgroundColor: marketingLine,
              color: marketingGreen,
            ),
          ),
        ],
      ],
    ),
  );
}

class _ReportHighlights extends StatelessWidget {
  const _ReportHighlights({
    required this.summary,
    required this.top,
    required this.centers,
  });

  final Map<String, dynamic> summary, top;

  final List<Map<String, dynamic>> centers;

  @override
  Widget build(BuildContext context) {
    final topCenters = [...centers]
      ..sort(
        (a, b) => marketingNumber(
          b['students_enrolled'],
        ).compareTo(marketingNumber(a['students_enrolled'])),
      );

    final rows = topCenters.take(4).toList();

    final highest = rows.fold<int>(
      1,
      (max, row) => marketingNumber(row['students_enrolled']) > max
          ? marketingNumber(row['students_enrolled'])
          : max,
    );

    return Container(
      padding: const EdgeInsets.all(15),

      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: marketingLine),
      ),

      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          const Text(
            'CENTER HIGHLIGHTS',
            style: TextStyle(
              color: marketingMuted,
              fontSize: 10,
              letterSpacing: .9,
              fontWeight: FontWeight.w800,
            ),
          ),

          const SizedBox(height: 10),

          if (top.isNotEmpty)
            Container(
              padding: const EdgeInsets.all(11),
              color: const Color(0xFFEAF3EE),
              child: Row(
                children: [
                  Container(
                    width: 34,
                    height: 34,
                    color: Colors.white,
                    child: const Icon(
                      Icons.emoji_events_outlined,
                      color: Color(0xFF9B6A13),
                      size: 19,
                    ),
                  ),

                  const SizedBox(width: 9),

                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          'Leading service center',
                          style: TextStyle(color: marketingMuted, fontSize: 10),
                        ),

                        Text(
                          '${top['name'] ?? 'Service center'}',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            color: marketingGreenDark,
                            fontWeight: FontWeight.w900,
                            fontSize: 13,
                          ),
                        ),
                      ],
                    ),
                  ),

                  Text(
                    '${marketingNumber(top['students_enrolled'])}',
                    style: const TextStyle(
                      color: marketingGreen,
                      fontSize: 18,
                      fontWeight: FontWeight.w900,
                    ),
                  ),
                ],
              ),
            ),

          if (rows.isNotEmpty) ...[
            const SizedBox(height: 12),

            const Text(
              'Enrollment by center',
              style: TextStyle(
                color: marketingInk,
                fontSize: 12,
                fontWeight: FontWeight.w800,
              ),
            ),

            const SizedBox(height: 6),

            ...rows.map((row) {
              final count = marketingNumber(row['students_enrolled']);

              final value = (count / highest).clamp(0.0, 1.0).toDouble();

              return Padding(
                padding: const EdgeInsets.only(top: 7),
                child: Row(
                  children: [
                    SizedBox(
                      width: 115,
                      child: Text(
                        '${row['center_name'] ?? 'Center'}',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                          color: marketingMuted,
                          fontSize: 11,
                        ),
                      ),
                    ),

                    const SizedBox(width: 8),

                    Expanded(
                      child: ClipRect(
                        child: LinearProgressIndicator(
                          value: value,
                          minHeight: 7,
                          backgroundColor: marketingLine,
                          color: marketingGreen,
                        ),
                      ),
                    ),

                    const SizedBox(width: 8),

                    SizedBox(
                      width: 36,
                      child: Text(
                        '$count',
                        textAlign: TextAlign.right,
                        style: const TextStyle(
                          color: marketingInk,
                          fontSize: 11,
                          fontWeight: FontWeight.w800,
                        ),
                      ),
                    ),
                  ],
                ),
              );
            }),
          ] else
            const SizedBox(
              height: 88,
              child: Center(
                child: Text(
                  'Center comparisons will appear as indicators are recorded.',
                  textAlign: TextAlign.center,
                  style: TextStyle(color: marketingMuted, fontSize: 12),
                ),
              ),
            ),
        ],
      ),
    );
  }
}

class _DonutPainter extends CustomPainter {
  const _DonutPainter({required this.attainment});

  final int? attainment;

  @override
  void paint(Canvas canvas, Size size) {
    final rect = Rect.fromLTWH(6, 6, size.width - 12, size.height - 12);

    const stroke = 12.0;

    final base = Paint()
      ..color = marketingLine
      ..style = PaintingStyle.stroke
      ..strokeWidth = stroke;

    final foreground = Paint()
      ..color = marketingGreen
      ..style = PaintingStyle.stroke
      ..strokeWidth = stroke
      ..strokeCap = StrokeCap.butt;

    canvas.drawArc(rect, -1.5708, 6.2832, false, base);

    if (attainment != null)
      canvas.drawArc(
        rect,
        -1.5708,
        6.2832 * (attainment!.clamp(0, 100) / 100),
        false,
        foreground,
      );
  }

  @override
  bool shouldRepaint(covariant _DonutPainter oldDelegate) =>
      oldDelegate.attainment != attainment;
}
