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

import '../../../../../../../common/theme/theme.dart';
import '../../../../../../../domain/analytic/analytic.dart';

class ReportProfitLossTrendChart extends StatelessWidget {
  final List<ProfitLossAnalyticItem> data;
  const ReportProfitLossTrendChart({super.key, required this.data});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      margin: const EdgeInsets.only(top: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Analisis Tren Keuntungan',
                style: AppStyle.xl.copyWith(
                  fontWeight: FontWeight.bold,
                  color: AppColor.textPrimary,
                ),
              ),
              Row(
                children: [
                  _buildLegendItem('Pendapatan', AppColor.info),
                  const SizedBox(width: 16),
                  _buildLegendItem('Biaya', AppColor.error),
                  const SizedBox(width: 16),
                  _buildLegendItem('Laba Bersih', AppColor.success),
                ],
              ),
            ],
          ),
          const SizedBox(height: 20),
          SizedBox(
            height: 220,
            child: LineChart(
              LineChartData(
                gridData: FlGridData(
                  show: true,
                  drawHorizontalLine: true,
                  drawVerticalLine: false,
                  horizontalInterval: 100000,
                  getDrawingHorizontalLine: (value) {
                    return FlLine(color: Colors.grey[100]!, strokeWidth: 1);
                  },
                ),
                titlesData: FlTitlesData(
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      reservedSize: 50,
                      getTitlesWidget: (value, meta) {
                        final kValue = (value / 1000);
                        if (kValue.isFinite) {
                          return Text(
                            '${kValue.toInt()}K',
                            style: AppStyle.xs.copyWith(
                              color: AppColor.textSecondary,
                              fontSize: 10,
                            ),
                          );
                        }
                        return const SizedBox();
                      },
                    ),
                  ),
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: (value, meta) {
                        final index = value.toInt();
                        if (index >= 0 && index < data.length) {
                          final date = DateTime.parse(data[index].date);
                          return Padding(
                            padding: const EdgeInsets.only(top: 8),
                            child: Text(
                              '${date.day}/${date.month}',
                              style: AppStyle.xs.copyWith(
                                color: AppColor.textSecondary,
                                fontSize: 10,
                              ),
                            ),
                          );
                        }
                        return const SizedBox();
                      },
                    ),
                  ),
                  rightTitles: const AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  topTitles: const AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                ),
                borderData: FlBorderData(show: false),
                lineBarsData: [
                  // Garis Pendapatan
                  LineChartBarData(
                    spots: data.asMap().entries.map((entry) {
                      final revenue = entry.value.revenue.toDouble();
                      return FlSpot(
                        entry.key.toDouble(),
                        revenue.isFinite ? revenue : 0,
                      );
                    }).toList(),
                    isCurved: true,
                    color: AppColor.info,
                    dotData: const FlDotData(show: false),
                  ),
                  // Garis Biaya
                  LineChartBarData(
                    spots: data.asMap().entries.map((entry) {
                      final cost = entry.value.cost.toDouble();
                      return FlSpot(
                        entry.key.toDouble(),
                        cost.isFinite ? cost : 0,
                      );
                    }).toList(),
                    isCurved: true,
                    color: AppColor.error,
                    dotData: const FlDotData(show: false),
                  ),
                  // Garis Laba Bersih
                  LineChartBarData(
                    spots: data.asMap().entries.map((entry) {
                      final netProfit = entry.value.netProfit.toDouble();
                      return FlSpot(
                        entry.key.toDouble(),
                        netProfit.isFinite ? netProfit : 0,
                      );
                    }).toList(),
                    isCurved: true,
                    color: AppColor.success,
                    dotData: const FlDotData(show: true),
                    belowBarData: BarAreaData(
                      show: true,
                      color: AppColor.success.withOpacity(0.1),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLegendItem(String label, Color color) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 12,
          height: 12,
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(2),
          ),
        ),
        const SizedBox(width: 6),
        Text(
          label,
          style: AppStyle.sm.copyWith(
            fontSize: 12,
            fontWeight: FontWeight.w500,
            color: AppColor.textPrimary,
          ),
        ),
      ],
    );
  }
}
