import 'dart:convert';

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

import '../../../views/widgets/error_snakbar.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 == 'success') {
      try {
        monthlyList = jsonDecode(res)['message'];
      } catch (e) {
        monthlyList = [];
      }
    } else {
      monthlyList = [];
    }

    isLoading = false;
    update();
  }

  Future<void> fetchData() async {
    isLoading = true;
    update();

    var res = await CRUD().get(
      link: AppLink.getTotalDriverDuration,
      payload: {'driver_id': box.read(BoxName.driverID)},
    );

    if (res == 'success') {
      try {
        jsonData1 = jsonDecode(res);
        final List<dynamic> jsonData = jsonData1['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;
      } catch (e) {
        jsonData1 = {};
        chartData = <FlSpot>[];
      }
    } else {
      jsonData1 = {};
      chartData = <FlSpot>[];
    }

    isLoading = false;
    update();
  }

  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' && res != 'no_internet' && res != 'token_expired') {
      jsonData2 = jsonDecode(res);
      var jsonResponse = jsonData2 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();
    } else {
      isLoading = false;
      jsonData2 = {};
      chartRideCount = <FlSpot>[];
      chartRidePriceDriver = <FlSpot>[];
      update();

      if (res == 'no_internet') {
        mySnackeBarError('No internet connection'.tr);
      }
    }
  }

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