import 'dart:convert';

import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/models/model/driver/rides_summary_model.dart';

class DurationController extends GetxController {
  final data = DurationData;
  // late AnimationController animationController;
  late List<MonthlyDataModel> rideData;
  late List<MonthlyRideModel> rideCountData;
  late List<MonthlyPriceDriverModel> ridePriceDriverData;
  Map<String, dynamic> jsonData1 = {};
  Map<String, dynamic> jsonData2 = {};
  bool isLoading = false;
  String totalDurationToday = '';
  var chartData;
  var chartRideCount;
  var chartRidePriceDriver;
  List monthlyList = [];

  @override
  void onInit() async {
    super.onInit();
    await fetchData();
    await fetchRideDriver();
    await getStaticDriver();
  }

  getStaticDriver() async {
    isLoading = true;
    update();
    var res = await CRUD().get(
        link: AppLink.driverStatistic,
        payload: {'driverID': box.read(BoxName.driverID)});
    if (res == 'failure') {
      monthlyList = [];
      isLoading = false;
      update();
    } else {
      monthlyList = jsonDecode(res)['message'];
      isLoading = false;
      update();
    }
  }

  Future<void> fetchData() async {
    isLoading = true;
    update(); // Notify the observers about the loading state change

    var res = await CRUD().get(
      link: AppLink.getTotalDriverDuration,
      payload: {'driver_id': box.read(BoxName.driverID)},
    );
    jsonData1 = jsonDecode(res);
    var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
    isLoading = false;
    final List<dynamic> jsonData = jsonResponse['message'];
    rideData = jsonData.map<MonthlyDataModel>((item) {
      return MonthlyDataModel.fromJson(item);
    }).toList();
    final List<FlSpot> spots = rideData
        .map((data) => FlSpot(
              data.day.toDouble(),
              data.totalDuration.toDouble(),
            ))
        .toList();
    chartData = spots;

    update(); // Notify the observers about the data and loading state change
  }

  Future<void> fetchRideDriver() async {
    isLoading = true;
    update(); // Notify the observers about the loading state change

    var res = await CRUD().get(
      link: AppLink.getRidesDriverByDay,
      payload: {'driver_id': box.read(BoxName.driverID)},
    );
    if (res != 'failure') {
      jsonData2 = jsonDecode(res);
      var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
      isLoading = false;
      final List<dynamic> jsonData = jsonResponse['message'];
      rideCountData = jsonData.map<MonthlyRideModel>((item) {
        return MonthlyRideModel.fromJson(item);
      }).toList();
      ridePriceDriverData = jsonData.map<MonthlyPriceDriverModel>((item) {
        return MonthlyPriceDriverModel.fromJson(item);
      }).toList();

      final List<FlSpot> spots = rideCountData
          .map((data) => FlSpot(
                data.day.toDouble(),
                data.countRide.toDouble(),
              ))
          .toList();
      chartRideCount = spots;
      final List<FlSpot> spotsDriverPrices = ridePriceDriverData
          .map((data) => FlSpot(
                data.day.toDouble(),
                data.pricePerDay.toDouble(),
              ))
          .toList();
      chartRidePriceDriver = spotsDriverPrices;

      update(); // Notify the observers about the data and loading state change
    } else {
      Get.defaultDialog(
          title: 'No data yet!'.tr,
          middleText: '',
          confirm: MyElevatedButton(
              title: 'OK'.tr,
              onPressed: () {
                Get.back();
                Get.back();
              }));
    }
  }

  List<DurationData> parseData(List<dynamic> json) {
    return json.map((entry) {
      final Map<String, dynamic> entryMap = entry;
      final day = DateTime.parse(entryMap['day']);
      final totalDuration = _parseDuration(entryMap['total_duration']);
      return DurationData(day, totalDuration);
    }).toList();
  }

  Duration _parseDuration(String durationString) {
    final parts = durationString.split(':');
    final hours = int.parse(parts[0]);
    final minutes = int.parse(parts[1]);
    final seconds = int.parse(parts[2]);
    return Duration(hours: hours, minutes: minutes, seconds: seconds);
  }
}

class DurationData {
  final DateTime day;
  final Duration totalDuration;

  DurationData(this.day, this.totalDuration);
}
