import 'package:design_system/design_system.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:krow_domain/krow_domain.dart';

class EarningsGraph extends StatelessWidget {

  const EarningsGraph({
    super.key,
    required this.payments,
    required this.period,
  });
  final List<StaffPayment> payments;
  final String period;

  @override
  Widget build(BuildContext context) {
    // Basic data processing for the graph
    // We'll aggregate payments by date
    final List<StaffPayment> validPayments = payments.where((StaffPayment p) => p.paidAt != null).toList()
      ..sort((StaffPayment a, StaffPayment b) => a.paidAt!.compareTo(b.paidAt!));

    // If no data, show empty state or simple placeholder
    if (validPayments.isEmpty) {
      return Container(
        height: 200,
        decoration: BoxDecoration(
          color: UiColors.white,
          borderRadius: BorderRadius.circular(UiConstants.radiusBase),
        ),
        child: Center(
          child: Text(
            "No sufficient data for graph",
            style: UiTypography.body2r.textSecondary,
          ),
        ),
      );
    }

    final List<FlSpot> spots = _generateSpots(validPayments);
    final double maxY = spots.isNotEmpty ? spots.map((FlSpot s) => s.y).reduce((double a, double b) => a > b ? a : b) : 0.0;

    return Container(
      height: 220,
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.white,
        borderRadius: BorderRadius.circular(UiConstants.radiusBase),
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: UiColors.black.withValues(alpha: 0.05),
            offset: const Offset(0, 4),
            blurRadius: 12,
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            "Earnings Trend",
            style: UiTypography.body2b.textPrimary,
          ),
          const SizedBox(height: UiConstants.space4),
          Expanded(
            child: LineChart(
              LineChartData(
                gridData: const FlGridData(show: false),
                titlesData: FlTitlesData(
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: (double value, TitleMeta meta) {
                        // Simple logic to show a few dates
                         if (value % 2 != 0) return const SizedBox();
                         final int index = value.toInt();
                         if (index >= 0 && index < validPayments.length) {
                           return Padding(
                             padding: const EdgeInsets.only(top: 8.0),
                             child: Text(
                               DateFormat('d').format(validPayments[index].paidAt!),
                               style: UiTypography.footnote1r.textSecondary,
                             ),
                           );
                         }
                         return const SizedBox();
                      },
                    ),
                  ),
                  leftTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
                  topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
                  rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
                ),
                borderData: FlBorderData(show: false),
                lineBarsData: <LineChartBarData>[
                  LineChartBarData(
                    spots: spots,
                    isCurved: true,
                    color: UiColors.primary,
                    barWidth: 3,
                    isStrokeCapRound: true,
                    dotData: const FlDotData(show: false),
                    belowBarData: BarAreaData(
                      show: true,
                      color: UiColors.primary.withValues(alpha: 0.1),
                    ),
                  ),
                ],
                minX: 0,
                maxX: (spots.length - 1).toDouble(),
                minY: 0,
                maxY: maxY * 1.2,
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<FlSpot> _generateSpots(List<StaffPayment> data) {
    // Generate spots based on index in the list for simplicity in this demo
    // Real implementation would map to actual dates on X-axis
    return List<FlSpot>.generate(data.length, (int index) {
      return FlSpot(index.toDouble(), data[index].amount);
    });
  }
}
