import 'package:doctor_app_flutter/util/date-utils.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 = List();
  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 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,
                ),
                Text(
                  widget.title,
                  style: TextStyle(
                      color: Colors.black,
                      fontSize: 32,
                      fontWeight: FontWeight.bold,
                      letterSpacing: 2),
                  textAlign: TextAlign.center,
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(right: 16.0, left: 6.0),
                    child: LineChart(
                      sampleData1(),
                      swapAnimationDuration: const Duration(milliseconds: 250),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  LineChartData sampleData1() {
    return LineChartData(
      lineTouchData: LineTouchData(
        touchTooltipData: LineTouchTooltipData(
          tooltipBgColor: Colors.white,
        ),
        touchCallback: (LineTouchResponse touchResponse) {},
        handleBuiltInTouches: true,
      ),
      gridData: FlGridData(
          show: true, drawVerticalLine: true, drawHorizontalLine: true),
      titlesData: FlTitlesData(
        bottomTitles: SideTitles(
          showTitles: true,
          getTextStyles: (value) => const TextStyle(
            color: Colors.black,
            fontSize: 12,
          ),
          margin: 22,
          rotateAngle:-65,
          getTitles: (value) {
            print(value);
            DateTime date = DateUtils.convertStringToDate(widget.labResult[value.toInt()].verifiedOnDateTime);
            if (widget.labResult.length < 8) {
              if (widget.labResult.length > value.toInt()) {
                return '${date.day}/ ${date.year}';
              } else
                return '';
            } else {
              if (value.toInt() == 0)
                return '${date.day}/ ${date.year}';
              if (value.toInt() == widget.labResult.length - 1)
                return '${date.day}/ ${date.year}';
              if (xAxixs.contains(value.toInt())) {
                return '${date.day}/ ${date.year}';
              }
            }



            return '';
          },
        ),
        leftTitles: SideTitles(
          showTitles: true,
          getTextStyles: (value) => const TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.bold,
            fontSize: 10,
          ),
          getTitles: (value) {
            return '${value.toInt()}';
          },
          margin: 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.labResult.length - 1).toDouble(),
      maxY: getMaxY(),
      minY: getMinY(),
      lineBarsData: getData(),
    );
  }

  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);
      }
    });

    return max.roundToDouble();
  }

  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();

    return value.toDouble();
  }

  List<LineChartBarData> getData() {
    List<FlSpot> spots = List();
    for (int index = 0; index < widget.labResult.length; index++) {
      try{
      var resultValueDouble = double.parse(widget.labResult[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,
      colors: [Theme.of(context).primaryColor],
      barWidth: 5,
      isStrokeCapRound: true,
      dotData: FlDotData(
        show: false,
      ),
      belowBarData: BarAreaData(
        show: false,
      ),
    );

    return [
      lineChartBarData1,
    ];
  }
}
