import 'dart:convert';

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

class DurationController extends GetxController {
  final data = DurationData;
  // late AnimationController animationController;
  late List<MonthlyDataModel> rideData;
  Map<String, dynamic> jsonData1 = {};
  bool isLoading = false;
  String totalDurationToday = '';
  var chartData;

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

  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;
    // print(jsonResponse);
    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
  }

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