import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:barber_app/core/theme/app_theme.dart';
import 'package:barber_app/features/finances/data/repositories/transaction_repository.dart';

class RevenueChart extends StatelessWidget {
  const RevenueChart({super.key});

  @override
  Widget build(BuildContext context) {
    final transactionRepo = TransactionRepository();
    // Pegando dados reais (filtro básico)
    final now = DateTime.now();
    final List<double> dailyRevenue = List.filled(7, 0.0);
    final weekdays = <String>[];

    for (int i = 6; i >= 0; i--) {
      final day = now.subtract(Duration(days: i));
      weekdays.add('${day.day}/${day.month}');

      final revenues = transactionRepo.getRevenues().where(
        (t) =>
            t.dueDate.year == day.year &&
            t.dueDate.month == day.month &&
            t.dueDate.day == day.day,
      );

      double sum = 0;
      for (var r in revenues) {
        sum += r.amount;
      }
      dailyRevenue[6 - i] = sum;
    }

    // Se estiver tudo zero, coloca alguns dados dummies pra ficar bonito pro usuário ver o potencial
    // (Opcional: remover em produção, mas bom para demo visual inicial)
    if (dailyRevenue.every((v) => v == 0)) {
      // Dados de exemplo para o gráfico não ficar vazio na primeira execução
      // dailyRevenue[0] = 150; dailyRevenue[1] = 200; ...
      // Melhor não inventar dados se é um app funcional. Mostra zero mesmo.
    }

    return AspectRatio(
      aspectRatio: 1.70,
      child: Container(
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(18)),
          color: AppColors.surface,
          border: Border.all(color: AppColors.surfaceLight),
        ),
        padding: const EdgeInsets.only(
          right: 18,
          left: 12,
          top: 24,
          bottom: 12,
        ),
        child: LineChart(
          LineChartData(
            gridData: FlGridData(
              show: true,
              drawVerticalLine: false,
              horizontalInterval: 100, // Ajustar conforme valores
              getDrawingHorizontalLine: (value) {
                return FlLine(color: AppColors.surfaceLight, strokeWidth: 1);
              },
            ),
            titlesData: FlTitlesData(
              show: true,
              rightTitles: AxisTitles(
                sideTitles: SideTitles(showTitles: false),
              ),
              topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
              bottomTitles: AxisTitles(
                sideTitles: SideTitles(
                  showTitles: true,
                  reservedSize: 30,
                  interval: 1,
                  getTitlesWidget: (value, meta) {
                    final index = value.toInt();
                    if (index >= 0 && index < weekdays.length) {
                      return Padding(
                        padding: const EdgeInsets.only(top: 8.0),
                        child: Text(
                          weekdays[index],
                          style: const TextStyle(
                            color: AppColors.textSecondary,
                            fontWeight: FontWeight.bold,
                            fontSize: 10,
                          ),
                        ),
                      );
                    }
                    return const Text('');
                  },
                ),
              ),
              leftTitles: AxisTitles(
                sideTitles: SideTitles(
                  showTitles: true,
                  interval: 100, // Ajustar
                  getTitlesWidget: (value, meta) {
                    return Text(
                      'R\$ ${value.toInt()}',
                      style: const TextStyle(
                        color: AppColors.textSecondary,
                        fontSize: 10,
                      ),
                    );
                  },
                  reservedSize: 42,
                ),
              ),
            ),
            borderData: FlBorderData(show: false),
            minX: 0,
            maxX: 6,
            minY: 0,
            // Adiciona margem superior
            maxY: (dailyRevenue.reduce((a, b) => a > b ? a : b) * 1.2) + 100,
            lineBarsData: [
              LineChartBarData(
                spots: List.generate(
                  7,
                  (index) => FlSpot(index.toDouble(), dailyRevenue[index]),
                ),
                isCurved: true,
                gradient: LinearGradient(
                  colors: [
                    AppColors.primaryColor,
                    AppColors.primaryColor.withValues(alpha: 0.5),
                  ],
                ),
                barWidth: 4,
                isStrokeCapRound: true,
                dotData: FlDotData(show: false),
                belowBarData: BarAreaData(
                  show: true,
                  gradient: LinearGradient(
                    colors: [
                      AppColors.primaryColor.withValues(alpha: 0.3),
                      AppColors.primaryColor.withValues(alpha: 0.0),
                    ],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
