import 'package:hmg_patient_app/uitl/date_uitl.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';

import '../../../../core/model/labs/LabOrderResult.dart';

class LineChartCurved extends StatefulWidget {
  final String? title;
  final List<LabOrderResult>? labResult;

  LineChartCurved({this.title, this.labResult});

  @override
  State<StatefulWidget> createState() => LineChartCurvedState();
}

class LineChartCurvedState extends State<LineChartCurved> {
  bool? isShowingMainData;
  List<int> xAxixs = [];
  int indexes = 0;

  @override
  void initState() {
    super.initState();
    getXaxix();
    isShowingMainData = true;
  }

  getXaxix() {
    indexes = widget.labResult!.length ~/ 3.5;
    for (int index = 0; index < widget.labResult!.length; index++) {
      int mIndex = indexes * index;
      if (mIndex < widget.labResult!.length) {
        xAxixs.add(mIndex);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(18)),
        // color: Colors.white,
      ),
      child: Stack(
        children: <Widget>[
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                widget.title!,
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.64, height: 25 / 16),
              ),
              SizedBox(height: 16),
              AspectRatio(
                aspectRatio: 333 / 288,
                child: Padding(
                  padding: EdgeInsets.only(right: 16.0, left: 6.0),
                  child: LineChart(
                    sampleData1(),
                    duration: const Duration(milliseconds: 250),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  LineChartData sampleData1() {
    return LineChartData(
      lineTouchData: LineTouchData(
        touchTooltipData: LineTouchTooltipData(
          // tooltipBgColor: Colors.white,
        ),
        touchCallback: (touchEvent, LineTouchResponse? touchResponse) {},
        handleBuiltInTouches: true,
      ),
      gridData: FlGridData(show: true, drawVerticalLine: false, drawHorizontalLine: true),
      titlesData: FlTitlesData(
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            getTitlesWidget: (value, titile) {
              TextStyle style = TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: 0, height: 18 / 12);
              print(value);
              DateTime date = DateUtil.convertStringToDate(widget.labResult![value.toInt()].verifiedOnDateTime!);
              if (widget.labResult!.length < 8) {
                if (widget.labResult!.length > value.toInt()) {
                  return Text(
                    '${date.day}/ ${date.year}',
                    style: style,
                  );
                } else
                  return SizedBox();
              } else {
                if (value.toInt() == 0)
                  return Text(
                    '${date.day}/ ${date.year}',
                    style: style,
                  );
                if (value.toInt() == widget.labResult!.length - 1)
                  return Text(
                    '${date.day}/ ${date.year}',
                    style: style,
                  );
                if (xAxixs.contains(value.toInt())) {
                  return Text(
                    '${date.day}/ ${date.year}',
                    style: style,
                  );
                }
              }

              return SizedBox();
            },
            //   margin: 8,
            //  rotateAngle: -0,
          ),
        ),
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            getTitlesWidget: (value, title) {
              TextStyle style = TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: 0, height: 18 / 12);
              return Text(
                '${value}',
                style: style,
              );
            },
            // margin: 8,
            interval: getInterval(),
            //reservedSize: 30,
          ),
        ),
      ),
      borderData: FlBorderData(
        show: false,
        // 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: 0,
      maxX: (widget.labResult!.length - 1).toDouble(),
      maxY: getMaxY(),
      minY: getMinY(),
      lineBarsData: getData(),
    );
  }

  double getInterval() {
    double interval = 0.0;
    interval = (getMaxY() - getMinY()) < 1.0 ? 0.05 : 3.0;
    // print("Interval: " + (getMaxY() - getMinY()).toString());
    // print("Interval: " + interval.toString());
    return interval;
  }

  double getMaxY() {
    double max = 0;
    widget.labResult!.forEach((element) {
      try {
        double resultValueDouble = double.parse(element.resultValue!);
        if (resultValueDouble > max) max = resultValueDouble;
      } catch (e) {
        print(e);
      }
    });
    // print("MaxY: " + max.toString());
    return max;
  }

  double getMinY() {
    double min = 0;
    try {
      min = double.parse(widget.labResult![0].resultValue!);

      widget.labResult!.forEach((element) {
        double resultValueDouble = double.parse(element.resultValue!);
        if (resultValueDouble < min) min = resultValueDouble;
      });
    } catch (e) {
      print(e);
    }
    // int value = min.toInt();
    // print("MinY: " + min.toString());
    return min;
  }

  List<LineChartBarData> getData() {
    List<FlSpot> spots = [];
    for (int index = 0; index < widget.labResult!.length; index++) {
      try {
        var resultValueDouble = double.parse(widget.labResult![index].resultValue!);
        print("$index:$resultValueDouble");
        spots.add(FlSpot(index.toDouble(), resultValueDouble));
      } catch (e) {
        print(e);
        spots.add(FlSpot(index.toDouble(), 0.0));
      }
    }

    final LineChartBarData lineChartBarData1 = LineChartBarData(
      spots: spots,
      isCurved: true,
      //preventCurveOverShooting : true,
      color: Color(0xffD02127),
      barWidth: 1.5,
      isStrokeCapRound: true,
      dotData: FlDotData(
        show: false,
      ),
      belowBarData: BarAreaData(
        show: false,
      ),
    );

    return [
      lineChartBarData1,
    ];
  }
}
