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 {
  final List<StaffPayment> payments;
  final String period;

  const EarningsGraph({
    super.key,
    required this.payments,
    required this.period,
  });

  @override
  Widget build(BuildContext context) {
    // Basic data processing for the graph
    // We'll aggregate payments by date
    final validPayments = payments.where((p) => p.paidAt != null).toList()
      ..sort((a, 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: Colors.white,
          borderRadius: BorderRadius.circular(16),
        ),
        child: const Center(child: Text("No sufficient data for graph")),
      );
    }

    final spots = _generateSpots(validPayments);
    final maxX = spots.isNotEmpty ? spots.last.x : 0.0;
    final maxY = spots.isNotEmpty ? spots.map((s) => s.y).reduce((a, b) => a > b ? a : b) : 0.0;

    return Container(
      height: 220,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            offset: const Offset(0, 4),
            blurRadius: 12,
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            "Earnings Trend",
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: Color(0xFF0F172A),
            ),
          ),
          const SizedBox(height: 16),
          Expanded(
            child: LineChart(
              LineChartData(
                gridData: const FlGridData(show: false),
                titlesData: FlTitlesData(
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: (value, meta) {
                        // Simple logic to show a few dates
                         if (value % 2 != 0) return const SizedBox();
                         final 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: const TextStyle(fontSize: 10, color: Colors.grey),
                             ),
                           );
                         }
                         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(
                    spots: spots,
                    isCurved: true,
                    color: const Color(0xFF0032A0),
                    barWidth: 3,
                    isStrokeCapRound: true,
                    dotData: const FlDotData(show: false),
                    belowBarData: BarAreaData(
                      show: true,
                      color: const Color(0xFF0032A0).withOpacity(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.generate(data.length, (index) {
      return FlSpot(index.toDouble(), data[index].amount);
    });
  }
}
