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

import '../../../../../../../common/extension/extension.dart';
import '../../../../../../../common/theme/theme.dart';
import '../../../../../../../domain/analytic/analytic.dart';
import '../../../../../../components/spaces/space.dart';

class ReportDashboardSalesChart extends StatelessWidget {
  final List<DashboardRecentSale> sales;
  const ReportDashboardSalesChart({super.key, required this.sales});

  @override
  Widget build(BuildContext context) {
    if (sales.isEmpty) {
      return const Center(child: Text('Tidak ada data penjualan'));
    }

    // Sort agar tanggal berurutan
    final sortedSales = List.of(
      sales,
    )..sort((a, b) => DateTime.parse(a.date).compareTo(DateTime.parse(b.date)));

    // Convert ke FlSpot berdasarkan tanggal
    final spots = sortedSales.map((sale) {
      final date = DateTime.parse(sale.date);
      return FlSpot(
        date.millisecondsSinceEpoch.toDouble(),
        sale.sales.toDouble(),
      );
    }).toList();

    // Batas min & max untuk X axis
    final minX = spots.first.x;
    final maxX = spots.last.x;

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Tren Penjualan Harian',
            style: AppStyle.xl.copyWith(
              fontWeight: FontWeight.bold,
              color: AppColor.textPrimary,
            ),
          ),
          const SpaceHeight(12),
          SizedBox(
            height: 220,
            child: LineChart(
              LineChartData(
                minX: minX,
                maxX: maxX,
                lineTouchData: LineTouchData(
                  touchTooltipData: LineTouchTooltipData(
                    fitInsideHorizontally: true,
                    fitInsideVertically: true,
                    getTooltipColor: (touchedSpot) => AppColor.primary,
                    getTooltipItems: (touchedSpots) {
                      return touchedSpots.map((spot) {
                        final date = DateTime.fromMillisecondsSinceEpoch(
                          spot.x.toInt(),
                        );
                        final sale = spot.y.toInt();

                        return LineTooltipItem(
                          '${date.toFormattedDate()}\n ${sale.currencyFormatRpV2}',
                          AppStyle.xs.copyWith(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        );
                      }).toList();
                    },
                  ),
                ),
                gridData: FlGridData(
                  show: true,
                  drawHorizontalLine: true,
                  drawVerticalLine: false,
                  horizontalInterval: 200000,
                  getDrawingHorizontalLine: (value) {
                    return FlLine(color: Colors.grey[200]!, strokeWidth: 1);
                  },
                ),
                titlesData: FlTitlesData(
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      reservedSize: 60,
                      getTitlesWidget: (value, meta) {
                        return Text(
                          '${(value / 1000).toInt()}K',
                          style: AppStyle.xs.copyWith(
                            color: AppColor.textSecondary,
                            fontSize: 10,
                          ),
                        );
                      },
                    ),
                  ),
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      interval: sortedSales.length <= 1
                          ? 1
                          : (maxX - minX) /
                              (sortedSales.length > 6 ? 6 : sortedSales.length),
                      getTitlesWidget: (value, meta) {
                        final date = DateTime.fromMillisecondsSinceEpoch(
                          value.toInt(),
                        );
                        final formatter = DateFormat('dd MMM');

                        // tampilkan hanya jika tanggal cocok dengan titik data sebenarnya
                        final match = sortedSales.any((s) {
                          final d = DateTime.parse(s.date);
                          return d.difference(date).inDays.abs() < 1;
                        });

                        if (!match) return const SizedBox();

                        return Padding(
                          padding: const EdgeInsets.only(top: 8),
                          child: Text(
                            formatter.format(date),
                            style: AppStyle.xs.copyWith(
                              color: AppColor.textSecondary,
                              fontSize: 10,
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                  rightTitles: const AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  topTitles: const AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                ),
                borderData: FlBorderData(show: false),

                lineBarsData: [
                  LineChartBarData(
                    spots: spots,
                    isCurved: true,
                    color: AppColor.primary,
                    dotData: const FlDotData(show: true),
                    belowBarData: BarAreaData(
                      show: true,
                      color: AppColor.primary.withOpacity(0.1),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
