import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/analytics/models/range_of_aqi.dart';
import 'package:syncrow_web/pages/analytics/modules/air_quality/helpers/range_of_aqi_charts_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/air_quality/widgets/aqi_type_dropdown.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/helpers/energy_management_charts_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class RangeOfAqiChart extends StatelessWidget {
  final List<RangeOfAqi> chartData;
  final AqiType selectedAqiType;

  const RangeOfAqiChart({
    super.key,
    required this.chartData,
    required this.selectedAqiType,
  });

  List<(List<double> values, Color color, Color? dotColor)> get _lines {
    final sortedData = List<RangeOfAqi>.from(chartData)
      ..sort((a, b) => a.date.compareTo(b.date));

    return [
      (
        sortedData.map((e) {
          final value = e.data.firstOrNull;
          return value?.max ?? 0;
        }).toList(),
        ColorsManager.maxPurple,
        ColorsManager.maxPurpleDot,
      ),
      (
        sortedData.map((e) {
          final value = e.data.firstOrNull;
          return value?.average ?? 0;
        }).toList(),
        Colors.white,
        null,
      ),
      (
        sortedData.map((e) {
          final value = e.data.firstOrNull;
          return value?.min ?? 0;
        }).toList(),
        ColorsManager.minBlue,
        ColorsManager.minBlueDot,
      ),
    ];
  }

  (double maxY, double interval) get _maxYForAqiType {
    const aqiMaxValues = <AqiType, (double maxY, double interval)>{
      AqiType.aqi: (401, 100),
      AqiType.pm25: (351, 50),
      AqiType.pm10: (501, 100),
      AqiType.hcho: (301, 50),
      AqiType.tvoc: (501, 50),
      AqiType.co2: (1251, 250),
    };

    return aqiMaxValues[selectedAqiType]!;
  }

  @override
  Widget build(BuildContext context) {
    return LineChart(
      LineChartData(
        minY: 0,
        maxY: _maxYForAqiType.$1,
        clipData: const FlClipData.vertical(),
        gridData: EnergyManagementChartsHelper.gridData(
          horizontalInterval: _maxYForAqiType.$2,
        ),
        titlesData: RangeOfAqiChartsHelper.titlesData(
          context,
          chartData,
          leftSideInterval: _maxYForAqiType.$2,
        ),
        borderData: EnergyManagementChartsHelper.borderData(),
        lineTouchData: RangeOfAqiChartsHelper.lineTouchData(chartData),
        betweenBarsData: [
          BetweenBarsData(
            fromIndex: 0,
            toIndex: 2,
            gradient: LinearGradient(
              begin: Alignment.bottomCenter,
              end: Alignment.topCenter,
              stops: const [0.0, 0.2, 0.4, 0.6, 0.8, 1.0],
              colors: RangeOfAqiChartsHelper.gradientData.map((e) {
                final (color, _) = e;
                return color.withValues(alpha: 0.6);
              }).toList(),
            ),
          ),
        ],
        lineBarsData: _lines.map((e) {
          final (values, color, dotColor) = e;
          return _buildLine(values: values, color: color, dotColor: dotColor);
        }).toList(),
      ),
      duration: Duration.zero,
    );
  }

  FlDotData _buildDotData(Color color) {
    return FlDotData(
      show: true,
      getDotPainter: (_, __, ___, ____) => FlDotCirclePainter(
        radius: 2,
        color: ColorsManager.whiteColors,
        strokeWidth: 2,
        strokeColor: color,
      ),
    );
  }

  LineChartBarData _buildLine({
    required List<double> values,
    required Color color,
    Color? dotColor,
  }) {
    const invisibleDot = FlDotData(show: false);
    return LineChartBarData(
      spots: List.generate(values.length, (i) => FlSpot(i.toDouble(), values[i])),
      isCurved: true,
      color: color,
      barWidth: 4,
      isStrokeCapRound: true,
      dotData: dotColor != null ? _buildDotData(dotColor) : invisibleDot,
      belowBarData: BarAreaData(show: false),
    );
  }
}
