import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/model/charts/app_time_series_chart.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_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 LineChartCurvedBloodPressure extends StatelessWidget {
  final String title;
  final List<TimeSeriesSales2>? timeSeries1;
  final List<TimeSeriesSales2>? timeSeries2;
  final int indexes;
  final bool isOX;

  LineChartCurvedBloodPressure({this.title = '', this.timeSeries1, this.indexes = 0, this.timeSeries2, this.isOX = false});

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

  @override
  Widget build(BuildContext context) {
    getXaxix();
    return AspectRatio(
      aspectRatio: 1.1,
      child: Container(
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(18)),
          // color: Colors.white,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            const SizedBox(
              height: 4,
            ),
            Container(
              padding: const EdgeInsets.only(right: 18.0, left: 16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  AppText(
                    title,
                    fontSize: SizeConfig.textMultiplier! * 2.1,
                    fontWeight: FontWeight.bold,
                    fontFamily: 'Poppins',
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 10,
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(right: 18.0, left: 16.0, top: 15),
                child: LineChart(
                  sampleData1(context),
                  duration: const Duration(milliseconds: 250),
                ),
              ),
            ),
            SizedBox(
              height: 10,
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Row(
                  children: [
                    Container(
                      width: 20,
                      height: 20,
                      decoration: BoxDecoration(shape: BoxShape.rectangle, color: Theme.of(context).primaryColor),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    AppText(isOX ? "SAO2" : TranslationBase.of(context).systolicLng)
                  ],
                ),
                SizedBox(
                  width: 15,
                ),
                Row(
                  children: [
                    Container(
                      width: 20,
                      height: 20,
                      decoration: BoxDecoration(shape: BoxShape.rectangle, color: Colors.red),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    AppText(
                      isOX ? "FIO2" : TranslationBase.of(context).diastolicLng,
                    )
                  ],
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

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

  LineChartData sampleData1(context) {
    return LineChartData(
      lineTouchData: LineTouchData(
        touchTooltipData: LineTouchTooltipData(
          tooltipBgColor: Colors.white,
        ),
        touchCallback: (event, LineTouchResponse? touchResponse) {},
        handleBuiltInTouches: true,
      ),
      gridData: FlGridData(show: true, drawVerticalLine: true, drawHorizontalLine: true),
      titlesData: FlTitlesData(
        bottomTitles: AxisTitles(
            sideTitles: SideTitles(
          showTitles: true,
          //rotateAngle: -65,
          //rotateAngle:-65,
          reservedSize: 22,
          getTitlesWidget: (value, meta) {
            if (timeSeries1!.length < 15) {
              if (timeSeries1!.length > value.toInt()) {
                return Text(
                  '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 10,
                  ),
                );
              } else
                return Text("");
            } else {
              if (value.toInt() == 0)
                return Text(
                  '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 10,
                  ),
                );
              if (value.toInt() == timeSeries1!.length - 1)
                return Text('${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 10,
                    ));
              if (xAxixs.contains(value.toInt())) {
                return Text(
                  '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 10,
                  ),
                );
              }
            }
            return Text("");
          },
        )),
        leftTitles: AxisTitles(
            sideTitles: SideTitles(
          showTitles: true,
          interval: getInterval(),
          getTitlesWidget: (value, meta) {
            return Text(
              '${value.toInt()}',
              style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontSize: 10,
              ),
            );
          },
          reservedSize: 12,
        )),
      ),
      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: 0,
      maxY: getMaxY() + getInterval(),
      minY: 0,
      lineBarsData: getData(context),
    );
  }

  double getInterval() {
    return getMaxY() - getMinY() <= 100
        ? 20
        : getMaxY() - getMinY() <= 1000
            ? 100
            : 200;
  }

  double getMaxY() {
    double max = 0;
    timeSeries1!.forEach((element) {
      double resultValueDouble = element.sales!;
      if (resultValueDouble > max) max = resultValueDouble;
    });

    return max.roundToDouble();
  }

  double getMinY() {
    double min = timeSeries1![0].sales!;
    timeSeries1!.forEach((element) {
      double resultValueDouble = element.sales!;
      if (resultValueDouble < min) min = resultValueDouble;
    });
    int value = min.toInt();

    return value.toDouble();
  }

  // double getMaxY() {
  //   double max = 0;
  //   timeSeries1.forEach((element) {
  //     double resultValueDouble = element.sales;
  //     if (resultValueDouble > max) max = resultValueDouble;
  //   });
  //   timeSeries2.forEach((element) {
  //     double resultValueDouble = element.sales;
  //     if (resultValueDouble > max) max = resultValueDouble;
  //   });
  //
  //   return max.roundToDouble();
  // }
  //
  // double getMinY() {
  //   double min = timeSeries1[0].sales;
  //   timeSeries1.forEach((element) {
  //     double resultValueDouble = element.sales;
  //     if (resultValueDouble < min) min = resultValueDouble;
  //   });
  //   timeSeries2.forEach((element) {
  //     double resultValueDouble = element.sales;
  //     if (resultValueDouble < min) min = resultValueDouble;
  //   });
  //
  //   int value = min.toInt();
  //
  //   return value.toDouble();
  // }

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

    List<FlSpot> spots2 = [];
    for (int index = 0; index < timeSeries2!.length; index++) {
      spots2.add(FlSpot(index.toDouble(), timeSeries2![index].sales!));
    }

    final LineChartBarData lineChartBarData1 = LineChartBarData(
      spots: spots,
      isCurved: true,
      color: Theme.of(context).primaryColor,
      barWidth: 5,
      isStrokeCapRound: true,
      dotData: FlDotData(
        show: false,
      ),
      belowBarData: BarAreaData(
        show: false,
      ),
    );
    final LineChartBarData lineChartBarData2 = LineChartBarData(
      spots: spots2,
      isCurved: true,
      color: Colors.red,
      barWidth: 5,
      isStrokeCapRound: true,
      dotData: FlDotData(
        show: false,
      ),
      belowBarData: BarAreaData(
        show: false,
      ),
    );

    List<LineChartBarData> lineChartData = [];
    if (spots.isNotEmpty) {
      lineChartData.add(lineChartBarData1);
    }
    if (spots2.isNotEmpty) {
      lineChartData.add(lineChartBarData2);
    }
    return lineChartData;
    // return [lineChartBarData1, lineChartBarData2];
  }
}
