import 'dart:math';

import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class LineGraph extends ConsumerStatefulWidget {
  final lines = [[0,1,0,3,0,1,0],[1,0,1,0,4,0,1]];
  late final maxValue = lines.map((x)=>x.reduce(max)).reduce(max);

  LineGraph({super.key});

  @override
  ConsumerState<LineGraph> createState() => LineGraphState();
}

class LineGraphState extends ConsumerState<LineGraph> {

  final weekDays =  ["L", "M", "X", "J", "V", "S", "D"];
  String? timeSpan;
  late var days = weekDays;

  @override
  void initState() {
    timeSpan = "week";
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final theme = ref.watch(themePortProvider);

    return Container(
      padding: EdgeInsets.all(20),
      decoration: BoxDecoration(
        border: BoxBorder.fromLTRB(left: BorderSide(color: Colors.cyan, width: 5)),
        borderRadius: BorderRadius.all(Radius.circular(13)),
        color: theme.getColorFor(ThemeCode.backgroundPrimary)
      ),
      child: Column(
        spacing: 32,
        children: [
          Row(children: [
            Text("Gastos", style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18)),
            Spacer(),
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(8)),
                color: theme.getColorFor(ThemeCode.backgroundSecondary),
              ),
              child:
              CustomDropdown(
                value: timeSpan,
                items: [
                  Text("Hoy", style: TextStyle(fontSize: 14, letterSpacing: 0)),
                  Text("Esta semana", style: TextStyle(fontSize: 14, letterSpacing: 0)),
                  Text("Este mes", style: TextStyle(fontSize: 14, letterSpacing: 0))
                ],
                values: ["day", "week", "month"],
                onChanged: (value)=>{},
                color: Colors.transparent,
                width: 151,
              ),
            )
          ]),
          SizedBox(
          height: 160,
          child: LineChart(LineChartData(
            gridData: FlGridData(
              show: true,
              drawHorizontalLine: false,
              drawVerticalLine: true,
              verticalInterval: 1,
              getDrawingVerticalLine: (value)=>FlLine(strokeWidth: 43, color: theme.getColorFor(ThemeCode.backgroundSecondary))
            ),
            titlesData: FlTitlesData(
              bottomTitles: AxisTitles(
                sideTitles: SideTitles(
                  interval: 1,
                  showTitles: true,
                  reservedSize: 40,
                  getTitlesWidget: (double value, TitleMeta meta){
                    String text = weekDays[value.toInt()];

                    return SideTitleWidget(
                      space: 4,
                      meta: meta,
                      child: Expanded(child: Center(child: Text(text, style: TextStyle(fontSize: 12)))),
                    );
                  },
                ),
              ),
              leftTitles: AxisTitles(),
              topTitles: AxisTitles(),
              rightTitles: AxisTitles()
            ),
            lineTouchData: LineTouchData(
              touchTooltipData: LineTouchTooltipData(
                tooltipBorderRadius: BorderRadius.all(Radius.circular(7)),
                getTooltipColor: (spot) => theme.getColorFor(ThemeCode.buttonSecondary),
                getTooltipItems: (List<LineBarSpot> touchedSpots) {
                  return touchedSpots.map((LineBarSpot touchedSpot) {
                    return LineTooltipItem(
                      "${touchedSpot.y}€",
                      TextStyle(fontWeight: FontWeight.w500, fontSize: 14, color: theme.getColorFor(ThemeCode.textSecondary)),
                    );
                  }).toList();
                },
              ),
              getTouchedSpotIndicator: (
                  _,
                  indicators,
                  ) {
                return indicators
                    .map((int index) => const TouchedSpotIndicatorData(
                  FlLine(color: Colors.transparent),
                  FlDotData(show: false),
                ))
                    .toList();
              },
              touchSpotThreshold: 25,
              distanceCalculator:
                  (Offset touchPoint, Offset spotPixelCoordinates) =>
              (touchPoint - spotPixelCoordinates).distance,
            ),
            borderData: FlBorderData(
              show: true,
              border: Border(
                bottom: BorderSide(
                    color: Colors.lightBlue.withValues(alpha: 0.2),
                    width: 4
                ),
                left: const BorderSide(color: Colors.transparent),
                right: const BorderSide(color: Colors.transparent),
                top: const BorderSide(color: Colors.transparent),
              ),
            ),
            lineBarsData: List<LineChartBarData>.generate(widget.lines.length, (int i)=>
              LineChartBarData(
                isCurved: true,
                gradient: LinearGradient(
                  begin: Alignment.bottomCenter,
                  end: Alignment.topCenter,
                  colors: theme.getCardColorFor(i)
                ),
                barWidth: 5,
                isStrokeCapRound: true,
                dotData: const FlDotData(show: false),
                belowBarData: BarAreaData(show: false),
                spots: List<FlSpot>.generate(widget.lines[i].length, (int j){
                  return FlSpot(j.toDouble(), widget.lines[i][j].toDouble());
                })
              ),
            ),
            minX: 0,
            maxX: days.length-1,
            maxY: widget.maxValue.toDouble(),
            minY: 0,
          ))
          )
        ],
      ),
    );
  }

}