// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// impact_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/features/stats/models/stat_analysis.dart';

class ImpactBarChart extends StatelessWidget {
  final FactorImpactRanking ranking;

  const ImpactBarChart({
    super.key,
    required this.ranking,
  });

  @override
  Widget build(BuildContext context) {
    // Create data for chart (limited to top 5)
    final factors = ranking.impactingFactors.take(5).toList();
    final data = <BarChartGroupData>[];

    for (int i = 0; i < factors.length; i++) {
      final factor = factors[i];

      data.add(
        BarChartGroupData(
          x: i,
          barRods: [
            BarChartRodData(
              toY: factor.impactScore,
              color: factor.impactColor,
              width: 20,
              borderRadius:
                  const BorderRadius.vertical(top: Radius.circular(4)),
            ),
          ],
        ),
      );
    }

    return BarChart(
      BarChartData(
        alignment: BarChartAlignment.center,
        maxY: 1,
        minY: 0,
        barGroups: data,
        gridData: FlGridData(
          show: true,
          horizontalInterval: 0.25,
          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 < factors.length) {
                  final factorName = factors[value.toInt()].name;
                  // Format factor name for display
                  String displayName = factorName;
                  if (displayName.startsWith('Hormone: ')) {
                    displayName = displayName.substring(9);
                  } else if (displayName.startsWith('Emotion: ')) {
                    displayName = displayName.substring(9);
                  }

                  return Padding(
                    padding: const EdgeInsets.only(top: 8.0),
                    child: Text(
                      displayName,
                      style: AppTextStyles.bodySmall,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  );
                }
                return const SizedBox();
              },
              reservedSize: 30,
            ),
          ),
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              getTitlesWidget: (value, meta) {
                if (value >= 0 && value <= 1 && value % 0.25 == 0) {
                  return Padding(
                    padding: const EdgeInsets.only(right: 8.0),
                    child: Text(
                      '${(value * 100).toStringAsFixed(0)}%',
                      style: AppTextStyles.bodySmall,
                    ),
                  );
                }
                return const SizedBox();
              },
              reservedSize: 40,
            ),
          ),
        ),
        barTouchData: BarTouchData(
          touchTooltipData: BarTouchTooltipData(
            tooltipBgColor: Colors.blueGrey.withAlpha(180),
            getTooltipItem: (group, groupIndex, rod, rodIndex) {
              final factor = factors[group.x];
              return BarTooltipItem(
                '${factor.name}: ${(factor.impactScore * 100).toStringAsFixed(0)}%',
                const TextStyle(
                    color: Colors.white, fontWeight: FontWeight.bold),
              );
            },
          ),
        ),
      ),
    );
  }
}
