import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/charts/app_time_series_chart.dart' as chart;
import 'package:fl_chart/fl_chart.dart';

import 'package:flutter/material.dart';

import '../../Constants.dart';

class ShowChart extends StatelessWidget {
  final String? title;
  final List<chart.TimeSeriesSales2>? timeSeries;
  final int? indexes;
  final double horizontalInterval;
  final bool isWeeklyOrMonthly;

  ShowChart({this.title, this.timeSeries, this.indexes, this.horizontalInterval = 8.0, this.isWeeklyOrMonthly = false});

  List<int> xAxixs = [];
  List<double> yAxixs = [];

  double minY = 0;
  double maxY = 0;
  double intialY = 0;
  double lastY = 0;

  double minX = 0;
  double maxX = 0;
  double increasingY = 0;

  @override
  Widget build(BuildContext context) {
    getXaxix();
    getYaxix();
    getInitialY();
    calculateMaxAndMin();
    return AspectRatio(
      aspectRatio: 1.0,
      child: Container(
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(18)),
          // color: Colors.white,
        ),
        child: Stack(
          children: <Widget>[
            Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Text(
                        title!,
                        style: TextStyle(color: Colors.black, fontSize: 16, letterSpacing: -0.64, fontWeight: FontWeight.w600),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ],
                ),
                mHeight(10),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(right: 18.0, left: 16.0),
                    child: LineChart(
                      sampleData1(context),
                      duration: const Duration(milliseconds: 250),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  getXaxix() {
    for (int index = 0; index < timeSeries!.length; index++) {
      int mIndex = indexes! * index!;
      if (mIndex < timeSeries!.length) {
        xAxixs.add(mIndex);
      }
    }
  }

  getYaxix() {
    for (int index = 0; index < timeSeries!.length; index++) {
      int mIndex = indexes! * index!;
      if (mIndex < timeSeries!.length) {
        yAxixs.add(timeSeries![mIndex].sales);
      }
    }
  }

  LineChartData sampleData1(context) {
    return LineChartData(
      lineTouchData: LineTouchData(
        touchTooltipData: LineTouchTooltipData(
          // tooltipBgColor: Colors.white,
        ),
        touchCallback: (touchEvent, LineTouchResponse? touchResponse) {},
        handleBuiltInTouches: true,
      ),
      gridData: FlGridData(show: true, drawVerticalLine: true, drawHorizontalLine: true),
      titlesData: FlTitlesData(
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,

            getTitlesWidget: (value, title) {
              TextStyle style = TextStyle(
                color: Colors.black,
                fontSize: 10,
              );

              if (isWeeklyOrMonthly) {
                return Text(
                  '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year.toString().substring(2)}',
                  style: style,
                );
              } else {
                if (timeSeries!.length < 15) {
                  if (timeSeries!.length > value.toInt()) {
                    return Text(
                      '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year.toString().substring(2)}',
                      style: style,
                    );
                  } else
                    return Text(
                      '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year.toString().substring(2)}',
                      style: style,
                    );
                } else {
                  if (value.toInt() == 0)
                    return Text(
                      '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year.toString().substring(2)}',
                      style: style,
                    );
                  if (value.toInt() == timeSeries!.length - 1)
                    return Text(
                      '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year.toString().substring(2)}',
                      style: style,
                    );
                  if (xAxixs.contains(value.toInt())) {
                    return Text(
                      '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year.toString().substring(2)}',
                      style: style,
                    );
                  }
                }
                return Text(
                  '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year.toString().substring(2)}',
                  style: style,
                );
              }
            },

            // rotateAngle: -65,
            // margin: 22,
          ),
        ),
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            getTitlesWidget: (cxt, value) {
              var style = TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontSize: 10,
              );
              return Text(
                "",
                style: style,
              );
            },
            interval: _fetchLeftTileInterval(),
            //margin: 12,
          ),
        ),
        topTitles: AxisTitles(
          sideTitles: SideTitles(showTitles: false),
        ),
        rightTitles: AxisTitles(
          sideTitles: SideTitles(showTitles: false),
        ),
      ),
      borderData: FlBorderData(
        show: true,
        border: const Border(
          bottom: BorderSide(
            color: Colors.black,
            width: 0.5,
          ),
          left: BorderSide(
            color: Colors.black,
          ),
          // right: BorderSide(
          //   color: Colors.black,
          // ),
          // top: BorderSide(
          //   color: Colors.transparent,
          // ),
        ),
      ),
      minX: minX,
      maxX: maxX,
      maxY: lastY + 1,
      minY: intialY - 0.5,
      lineBarsData: getData(context),
    );
  }

  calculateMaxAndMin() {
    getMaxY();
    getMaxX();
    getMin();
    getMinY();
    try {
      increasingY = ((maxY - minY) / timeSeries!.length - 1) * 15;
      maxY += increasingY.abs();
      minY -= increasingY.abs();
    } catch (ex) {
      print(ex);
    }
  }

  double _fetchLeftTileInterval() {
    final interval = ((lastY - intialY) / 5).toDouble();
    return interval < 1.0 ? 1.0 : interval;
  }

  double getMaxY() {
    maxY = 0;
    timeSeries!.forEach((element) {
      double resultValueDouble = element.sales;
      if (resultValueDouble > maxY) {
        lastY = resultValueDouble;
        maxY = resultValueDouble;
      }
    });
    print("maxY " + lastY.toString());
    return maxY.roundToDouble();
  }

  double getInitialY() {
    try {
      intialY = timeSeries!.first.sales;
      timeSeries!.forEach((element) {
        double resultValueDouble = element.sales;
        if (resultValueDouble < intialY) intialY = resultValueDouble;
      });
    } catch (e) {
      intialY = 0;
    }

    print("minY " + intialY.toString());
    return intialY.roundToDouble();
  }

  getMaxX() {
    maxX = (timeSeries!.length - 1).toDouble();
  }

  double getMin() {
    minX = 0;
    timeSeries!.forEach((element) {
      double resultValueDouble = element.sales;
      if (resultValueDouble < minX) minX = resultValueDouble;
    });

    return minX.roundToDouble();
  }

  double getMinY() {
    minY = 0;
    timeSeries!.forEach((element) {
      double resultValueDouble = element.sales;
      if (resultValueDouble < minY) minY = resultValueDouble;
    });
    int value = minY.toInt();

    return value.toDouble();
  }

  List<LineChartBarData> getData(context) {
    List<FlSpot> spots = [];
    for (int index = 0; index < timeSeries!.length; index++) {
      spots.add(FlSpot(index.toDouble(), timeSeries![index].sales));
    }

    final LineChartBarData lineChartBarData1 = LineChartBarData(
      spots: spots,
      isCurved: true,
      color: secondaryColor,
      barWidth: 1.5,
      isStrokeCapRound: true,
      dotData: FlDotData(
        show: true,
      ),
      belowBarData: BarAreaData(
        show: false,
      ),
    );

    return [
      lineChartBarData1,
    ];
  }
}
