import 'dart:convert';

import 'package:flutter/animation.dart';
import 'package:get/get.dart';
import 'package:ride/constant/box_name.dart';
import 'package:ride/constant/links.dart';
import 'package:ride/controller/functions/crud.dart';
import 'package:ride/main.dart';

class DurationController extends GetxController
    with GetSingleTickerProviderStateMixin {
  final data = <DurationData>[].obs;
  late AnimationController animationController;

  @override
  void onInit() {
    super.onInit();
    fetchData();
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(
          milliseconds: 500), // Adjust the animation duration as needed
    );
    animationController.forward(); // Start the animation
  }

  @override
  void onClose() {
    animationController.dispose();
    super.onClose();
  }

  Map<String, dynamic> jsonData = {};
  bool isLoading = false;
  String totalDurationToday = '';
  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)},
    );

    jsonData = jsonDecode(res);

    final parsedData = parseData(jsonData['message']);
    data.value = parsedData;

    isLoading = false;
    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);
}
