import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/model/labs/lab_result_history.dart';
import 'package:doctor_app_flutter/utils/date-utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';

class LineChartCurvedLabHistory extends StatefulWidget {
  final String title;
  final List<LabResultHistory> labResultHistory;

  LineChartCurvedLabHistory({required this.title, required this.labResultHistory});

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

class LineChartCurvedLabHistoryState extends State<LineChartCurvedLabHistory> {
  List<int> xAxixs = [];
  int indexes = 0;

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

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

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 1.23,
      child: Container(
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(18)),
          // color: Colors.white,
        ),
        child: Stack(
          children: <Widget>[
            Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                const SizedBox(
                  height: 4,
                ),
                AppText(
                  widget.title,
                  fontSize: SizeConfig.textMultiplier! * 2.1,
                  fontWeight: FontWeight.bold,
                  fontFamily: 'Poppins',
                  textAlign: TextAlign.center,
                ),
                const SizedBox(
                  height: 12,
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(right: 16.0, left: 8.0),
                    child: LineChart(
                      sampleData1(),
                      duration: const Duration(milliseconds: 250),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  LineChartData sampleData1() {
    return LineChartData(
      lineTouchData: LineTouchData(
        touchTooltipData: LineTouchTooltipData(
          tooltipBgColor: Colors.white,
        ),
        touchCallback: (event, touchResponse) {},
        handleBuiltInTouches: true,
      ),
      gridData: FlGridData(show: true, drawVerticalLine: true, drawHorizontalLine: true),
      titlesData: FlTitlesData(
        bottomTitles: AxisTitles(
            sideTitles: SideTitles(
          showTitles: true,
          reservedSize: 28,
          // rotateAngle: -65,
          getTitlesWidget: (value, meta) {
            DateTime date = AppDateUtils.convertStringToDate(widget.labResultHistory[value.toInt()].verifiedOnDateTime!);
            if (widget.labResultHistory.length < 8) {
              if (widget.labResultHistory.length > value.toInt()) {
                return Text(
                  '${date.day}/ ${date.year}',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 10,
                  ),
                );
              } else
                return Text("");
            } else {
              if (value.toInt() == 0)
                return Text(
                  '${date.day}/ ${date.year}',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 10,
                  ),
                );
              if (value.toInt() == widget.labResultHistory.length - 1)
                return Text(
                  '${date.day}/ ${date.year}',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 10,
                  ),
                );
              if (xAxixs.contains(value.toInt())) {
                return Text(
                  '${date.day}/ ${date.year}',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 10,
                  ),
                );
              }
            }

            return Text("");
          },
        )),
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            getTitlesWidget: (value, meta) {
              return Text('${value.toInt()}',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 10,
                  ));
            },
            reservedSize: 8,
            //reservedSize: 30,
          ),
        ),
      ),
      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: 0,
      maxX: (widget.labResultHistory.length - 1).toDouble(),
      maxY: getMaxY() + 2,
      minY: getMinY(),
      lineBarsData: getData(),
    );
  }

  double getMaxY() {
    double max = 0;
    widget.labResultHistory.forEach((element) {
      try {
        double resultValueDouble = double.parse(element.resultValue!);
        if (resultValueDouble > max) max = resultValueDouble;
      } catch (e) {
        print(e);
      }
    });

    return max.roundToDouble();
  }

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

      widget.labResultHistory.forEach((element) {
        double resultValueDouble = double.parse(element.resultValue!);
        if (resultValueDouble < min) min = resultValueDouble;
      });
    } catch (e) {
      print(e);
    }
    int value = min.toInt();

    return value.toDouble();
  }

  List<LineChartBarData> getData() {
    List<FlSpot> spots = [];
    for (int index = 0; index < widget.labResultHistory.length; index++) {
      try {
        var resultValueDouble = double.parse(widget.labResultHistory[index].resultValue!);
        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,
      color: Colors.red,
      barWidth: 3,
      isStrokeCapRound: true,
      curveSmoothness: 0.12,
      dotData: FlDotData(
        show: false,
      ),
      belowBarData: BarAreaData(
        show: false,
      ),
    );

    return [
      lineChartBarData1,
    ];
  }
}
