import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:syncrow_web/pages/analytics/models/phases_energy_consumption.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/helpers/energy_management_charts_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class EnergyConsumptionByPhasesChart extends StatelessWidget {
  const EnergyConsumptionByPhasesChart({
    super.key,
    required this.energyData,
  });

  final List<PhasesEnergyConsumption> energyData;

  @override
  Widget build(BuildContext context) {
    return BarChart(
      BarChartData(

        gridData: EnergyManagementChartsHelper.gridData().copyWith(
          checkToShowHorizontalLine: (value) => true,
          horizontalInterval: 250,
        ),
        borderData: EnergyManagementChartsHelper.borderData(),
        barTouchData: _barTouchData(context),
        titlesData: _titlesData(context),
        barGroups: energyData.asMap().entries.map((entry) {
          final index = entry.key;
          final data = entry.value;

          return BarChartGroupData(
            x: index,
            barRods: [
              BarChartRodData(
                color: ColorsManager.vividBlue.withValues(alpha: 0.1),
                toY: data.energyConsumedA +
                    data.energyConsumedB +
                    data.energyConsumedC,
                rodStackItems: [
                  BarChartRodStackItem(
                    0,
                    data.energyConsumedA,
                    ColorsManager.vividBlue.withValues(alpha: 0.8),
                  ),
                  BarChartRodStackItem(
                    data.energyConsumedA,
                    data.energyConsumedA + data.energyConsumedB,
                    ColorsManager.vividBlue.withValues(alpha: 0.4),
                  ),
                  BarChartRodStackItem(
                    data.energyConsumedA + data.energyConsumedB,
                    data.energyConsumedA +
                        data.energyConsumedB +
                        data.energyConsumedC,
                    ColorsManager.vividBlue.withValues(alpha: 0.15),
                  ),
                ],
                width: 8,
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(8),
                  topRight: Radius.circular(8),
                ),
              ),
            ],
          );
        }).toList(),
      ),
      duration: Duration.zero,
    );
  }

  BarTouchData _barTouchData(BuildContext context) {
    return BarTouchData(
      touchTooltipData: BarTouchTooltipData(
        getTooltipColor: (touchTooltipItem) => ColorsManager.whiteColors,
        tooltipBorder: const BorderSide(
          color: ColorsManager.semiTransparentBlack,
        ),
        tooltipRoundedRadius: 16,
        tooltipPadding: const EdgeInsets.all(8),
        getTooltipItem: (group, groupIndex, rod, rodIndex) => getTooltipItem(
          context: context,
          group: group,
          groupIndex: groupIndex,
          rod: rod,
          rodIndex: rodIndex,
        ),
      ),
    );
  }

  BarTooltipItem? getTooltipItem({
    required BuildContext context,
    required BarChartGroupData group,
    required int groupIndex,
    required BarChartRodData rod,
    required int rodIndex,
  }) {
    final data = energyData;

    final date = DateFormat('dd/MM/yyyy').format(data[group.x.toInt()].date);
    final phaseA = data[group.x.toInt()].energyConsumedA;
    final phaseB = data[group.x.toInt()].energyConsumedB;
    final phaseC = data[group.x.toInt()].energyConsumedC;
    final total = data[group.x.toInt()].energyConsumedKw;

    return BarTooltipItem(
      '$date\n',
      context.textTheme.bodyMedium!.copyWith(
        color: ColorsManager.blackColor,
        fontSize: 14,
      ),
      textAlign: TextAlign.start,
      children: [
        TextSpan(
          text: 'Total: $total\n',
          style: context.textTheme.bodySmall?.copyWith(
            color: ColorsManager.blackColor,
            fontSize: 12,
          ),
        ),
        TextSpan(
          text: 'Phase A: $phaseA\n',
          style: context.textTheme.bodySmall?.copyWith(
            color: ColorsManager.blackColor,
            fontSize: 12,
          ),
        ),
        TextSpan(
          text: 'Phase B: $phaseB\n',
          style: context.textTheme.bodySmall?.copyWith(
            color: ColorsManager.blackColor,
            fontSize: 12,
          ),
        ),
        TextSpan(
          text: 'Phase C: $phaseC',
          style: context.textTheme.bodySmall?.copyWith(
            color: ColorsManager.blackColor,
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  FlTitlesData _titlesData(BuildContext context) {
    final titlesData = EnergyManagementChartsHelper.titlesData(
      context,
      leftTitlesInterval: 250,
    );

    final leftTitles = titlesData.leftTitles.copyWith(
      sideTitles: titlesData.leftTitles.sideTitles.copyWith(
        reservedSize: 70,
      ),
    );

    final bottomTitles = AxisTitles(
      sideTitles: SideTitles(
        showTitles: true,
        getTitlesWidget: (value, _) {
          final month = DateFormat('d').format(energyData[value.toInt()].date);
          return FittedBox(
            alignment: AlignmentDirectional.center,
            fit: BoxFit.scaleDown,
            child: RotatedBox(
              quarterTurns: 3,
              child: Text(
                month,
                style: context.textTheme.bodySmall?.copyWith(
                  color: ColorsManager.lightGreyColor,
                  fontSize: 11,
                ),
              ),
            ),
          );
        },
        reservedSize: 18,
      ),
    );

    return titlesData.copyWith(
      leftTitles: leftTitles,
      bottomTitles: bottomTitles,
    );
  }
}
