// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// weekday_chart.dart
//
import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:nokken/src/core/ui/theme/app_colors.dart';
import 'package:nokken/src/core/ui/theme/app_text_styles.dart';
import 'package:nokken/src/core/ui/theme/app_theme.dart';
import 'package:nokken/src/features/stats/models/stat_analysis.dart';

class WeekdayBarChart extends StatelessWidget {
  final WeekdayAnalysis analysis;
  final String factor;

  const WeekdayBarChart({
    super.key,
    required this.analysis,
    required this.factor,
  });

  @override
  Widget build(BuildContext context) {
    // Create data for chart
    final data = <BarChartGroupData>[];
    final dayLabels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

    for (int i = 1; i <= 7; i++) {
      final dayData = analysis.factorsByWeekday['$factor-$i'] ?? [];

      if (dayData.isNotEmpty) {
        final avgValue = dayData.reduce((a, b) => a + b) / dayData.length;

        Color barColor;
        if (analysis.bestDays[factor] == i) {
          barColor = Colors.green;
        } else if (analysis.worstDays[factor] == i) {
          barColor = Colors.red;
        } else {
          barColor = AppColors.primary;
        }

        data.add(
          BarChartGroupData(
            x: i - 1,
            barRods: [
              BarChartRodData(
                toY: avgValue,
                color: barColor,
                width: 20,
                borderRadius:
                    const BorderRadius.vertical(top: Radius.circular(4)),
              ),
            ],
          ),
        );
      } else {
        data.add(
          BarChartGroupData(
            x: i - 1,
            barRods: [
              BarChartRodData(
                toY: 0,
                color: AppTheme.grey,
                width: 20,
              ),
            ],
          ),
        );
      }
    }

    return BarChart(
      BarChartData(
        alignment: BarChartAlignment.center,
        maxY: 4,
        minY: 0,
        barGroups: data,
        gridData: FlGridData(
          show: true,
          horizontalInterval: 1,
          getDrawingHorizontalLine: (value) {
            return FlLine(
              color: AppColors.onSurfaceVariant.withAlpha(40),
              strokeWidth: 1,
            );
          },
        ),
        borderData: FlBorderData(
          show: true,
          border: Border.all(color: AppColors.onSurfaceVariant.withAlpha(40)),
        ),
        titlesData: FlTitlesData(
          show: true,
          topTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          rightTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              getTitlesWidget: (value, meta) {
                if (value >= 0 && value < 7) {
                  return Padding(
                    padding: const EdgeInsets.only(top: 8.0),
                    child: Text(
                      dayLabels[value.toInt()],
                      style: AppTextStyles.bodySmall,
                    ),
                  );
                }
                return const SizedBox();
              },
              reservedSize: 30,
            ),
          ),
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              getTitlesWidget: (value, meta) {
                if (value % 1 == 0 && value >= 0 && value <= 4) {
                  return Padding(
                    padding: const EdgeInsets.only(right: 8.0),
                    child: Text(
                      value.toInt().toString(),
                      style: AppTextStyles.bodySmall,
                    ),
                  );
                }
                return const SizedBox();
              },
              reservedSize: 30,
            ),
          ),
        ),
        barTouchData: BarTouchData(
          touchTooltipData: BarTouchTooltipData(
            tooltipBgColor: Colors.blueGrey.withAlpha(180),
            getTooltipItem: (group, groupIndex, rod, rodIndex) {
              final avg = rod.toY;
              return BarTooltipItem(
                '${dayLabels[group.x]} Avg: ${avg.toStringAsFixed(1)}',
                const TextStyle(
                    color: Colors.white, fontWeight: FontWeight.bold),
              );
            },
          ),
        ),
      ),
    );
  }
}
