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

class AqiDistributionChart extends StatelessWidget {
  const AqiDistributionChart({super.key, required this.chartData});
  final List<AirQualityDataModel> chartData;

  static const _rodStackItemsSpacing = 0.4;
  static const _barWidth = 13.0;
  static final _barBorderRadius = BorderRadius.circular(22);

  @override
  Widget build(BuildContext context) {
    return BarChart(
      BarChartData(
        maxY: 100.1,
        alignment: BarChartAlignment.start,
        gridData: EnergyManagementChartsHelper.gridData(
          horizontalInterval: 20,
        ),
        borderData: EnergyManagementChartsHelper.borderData(),
        barTouchData: _barTouchData(context),
        titlesData: _titlesData(context),
        barGroups: _buildBarGroups(),
      ),
      duration: Duration.zero,
    );
  }

  List<BarChartGroupData> _buildBarGroups() {
    final groups = <BarChartGroupData>[];
    for (var i = 0; i < chartData.length; i++) {
      final data = chartData[i];
      final isAllZero = data.data.every((d) => d.percentage == 0);
      if (isAllZero) {
        continue;
      }
      final stackItems = <BarChartRodData>[];
      double currentY = 0;
      var isFirstElement = true;

      for (final percentageData in data.data) {
        stackItems.add(
          BarChartRodData(
            fromY: currentY,
            toY: currentY + percentageData.percentage,
            color: AirQualityDataModel.metricColors[percentageData.type],
            borderRadius: isFirstElement
                ? const BorderRadius.only(
                    topLeft: Radius.circular(22),
                    topRight: Radius.circular(22),
                  )
                : _barBorderRadius,
            width: _barWidth,
          ),
        );
        currentY += percentageData.percentage + _rodStackItemsSpacing;
        isFirstElement = false;
      }
      groups.add(
        BarChartGroupData(
          x: i,
          barRods: stackItems,
          groupVertically: true,
        ),
      );
    }
    return groups;
  }

  BarTouchData _barTouchData(BuildContext context) {
    return BarTouchData(
      touchTooltipData: BarTouchTooltipData(
        getTooltipColor: (_) => ColorsManager.whiteColors,
        tooltipBorder: const BorderSide(
          color: ColorsManager.semiTransparentBlack,
        ),
        tooltipRoundedRadius: 16,
        maxContentWidth: 500,
        tooltipPadding: const EdgeInsets.all(8),
        getTooltipItem: (group, groupIndex, rod, rodIndex) {
          final data = chartData[group.x];

          final children = <TextSpan>[];

          final textStyle = context.textTheme.bodySmall?.copyWith(
            color: ColorsManager.blackColor,
            fontSize: 11,
          );

          for (final percentageData in data.data) {
            if (percentageData.percentage == 0) {
              continue;
            }
            final percentage = percentageData.percentage.toStringAsFixed(1);
            final type = percentageData.type[0].toUpperCase() +
                percentageData.type.substring(1).replaceAll('_', ' ');
            children.add(TextSpan(
              text: '\n$type: $percentage%',
              style: textStyle,
            ));
          }

          return BarTooltipItem(
            DateFormat('dd/MM/yyyy').format(data.date),
            context.textTheme.bodyMedium!.copyWith(
              color: ColorsManager.blackColor,
              fontSize: 12,
              fontWeight: FontWeight.w600,
            ),
            textAlign: TextAlign.start,
            children: children,
          );
        },
      ),
    );
  }

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

    final leftTitles = titlesData.leftTitles.copyWith(
      sideTitles: titlesData.leftTitles.sideTitles.copyWith(
        reservedSize: 70,
        maxIncluded: false,
        minIncluded: true,
        getTitlesWidget: (value, meta) => Padding(
          padding: const EdgeInsetsDirectional.only(end: 12),
          child: FittedBox(
            alignment: AlignmentDirectional.centerStart,
            fit: BoxFit.scaleDown,
            child: Text(
              '${value.toStringAsFixed(0)}%',
              style: context.textTheme.bodySmall?.copyWith(
                fontSize: 12,
                color: ColorsManager.lightGreyColor,
              ),
            ),
          ),
        ),
      ),
    );

    final bottomTitles = AxisTitles(
      axisNameWidget: const ChartsXAxisTitle(),
      sideTitles: SideTitles(
        showTitles: chartData.isNotEmpty,
        getTitlesWidget: (value, _) => FittedBox(
          alignment: AlignmentDirectional.bottomCenter,
          fit: BoxFit.scaleDown,
          child: Text(
            chartData[value.toInt()].date.day.toString(),
            style: context.textTheme.bodySmall?.copyWith(
              color: ColorsManager.lightGreyColor,
              fontSize: 12,
            ),
          ),
        ),
        reservedSize: 36,
      ),
    );

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