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/widgets/shared/app_texts_widget.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class LineChartCurved extends StatelessWidget {
  final String title;
  final List<TimeSeriesSales2>? timeSeries;
  final int indexes;

  LineChartCurved({this.title = '', this.timeSeries, this.indexes = 0});

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

  // DateFormat format = DateFormat("yyyy-MM-dd");
  DateFormat yearFormat = DateFormat("yyyy/MMM/dd");
  DateFormat monthFormat = DateFormat("dd/MMM");
  bool isDatesSameYear = true;

  @override
  Widget build(BuildContext context) {
    getXaxix();
    getYaxix();
    return AspectRatio(
      aspectRatio: 1.1,
      child: Container(
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(18)),
          // color: Colors.white,
        ),
        child: Stack(
          children: [
            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: 16,
                ),
                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() {
    int indexess = (timeSeries!.length * 0.30).toInt();
    for (int index = 0; index < timeSeries!.length; index++) {
      int mIndex = indexess * index;
      if (mIndex < timeSeries!.length) {
        yAxixs.add(timeSeries![mIndex].sales!);
      }
    }
  }

  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 (timeSeries!.length < 15) {
                if (timeSeries!.length > value.toInt()) {
                  DateTime dateTime = timeSeries![value.toInt()].time;
                  if (isDatesSameYear) {
                    return Text(
                      monthFormat.format(dateTime),
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 10,
                      ),
                    );
                  } else {
                    return Text(
                      yearFormat.format(dateTime),
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 10,
                      ),
                    );
                  }
                } else {
                  return Text('');
                }
              } else {
                if (value.toInt() == 0 || value.toInt() == timeSeries!.length - 1 || xAxixs.contains(value.toInt())) {
                  DateTime dateTime = timeSeries![value.toInt()].time;
                  if (isDatesSameYear) {
                    return Text(
                      monthFormat.format(dateTime),
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 10,
                      ),
                    );
                  } else {
                    return Text(
                      yearFormat.format(dateTime),
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 10,
                      ),
                    );
                  }
                }
              }
              return Text('');
            },
          ),
        ),
        leftTitles: AxisTitles(
            sideTitles: SideTitles(
          showTitles: true,
          interval: getInterval(),
          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: (timeSeries!.length - 1).toDouble(),
      maxY: getMaxY() + getInterval(),
      minY: 0,
      lineBarsData: getData(context),
    );
  }

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

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

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

    return max.roundToDouble();
  }

  double getMinY() {
    double min = timeSeries![0].sales!;
    timeSeries!.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 = [];
    isDatesSameYear = true;
    int previousDateYear = 0;
    for (int index = 0; index < timeSeries!.length; index++) {
      spots.add(FlSpot(index.toDouble(), timeSeries![index].sales!));
      if (isDatesSameYear == false || (previousDateYear != 0 && previousDateYear != timeSeries![index].time.year)) {
        isDatesSameYear = false;
      }
      previousDateYear = timeSeries![index].time.year;
    }

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

    return [
      lineChartBarData1,
    ];
  }
}
