import 'dart:convert';

import 'package:get/get.dart';
import 'package:ride/constant/box_name.dart';
import 'dart:async';

import '../../../constant/links.dart';
import '../../../main.dart';
import '../../functions/crud.dart';
import '../../functions/location_controller.dart';

class HomeCaptainController extends GetxController {
  bool isActive = false;
  DateTime? activeStartTime;
  Duration activeDuration = Duration.zero;
  Timer? activeTimer;
  Map data = {};
  String totalMoneyToday = '0';
  String totalDurationToday = '0';
  Timer? timer;
// Inject the LocationController class
  final locationController = Get.find<LocationController>();

  void onButtonSelected() {
    isActive = !isActive;
    if (isActive) {
      locationController.startLocationUpdates();
      activeStartTime = DateTime.now();
      activeTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
        activeDuration = DateTime.now().difference(activeStartTime!);
        update();
      });
    } else {
      locationController.stopLocationUpdates();

      activeStartTime = null;
      activeTimer?.cancel();
      savePeriod(activeDuration);
      activeDuration = Duration.zero;
    }
    update();
  }

  void savePeriod(Duration period) {
    final periods = box.read<List<dynamic>>(BoxName.periods) ?? [];
    periods.add(period.inSeconds);
    box.write(BoxName.periods, periods);
  }

  Duration calculateTotalDuration() {
    final periods = box.read<List<dynamic>>(BoxName.periods) ?? [];
    Duration totalDuration = Duration.zero;
    for (dynamic periodInSeconds in periods) {
      final periodDuration = Duration(seconds: periodInSeconds);
      totalDuration += periodDuration;
    }
    return totalDuration;
  }

  void startPeriodicExecution() {
    Timer.periodic(const Duration(seconds: 30), (timer) async {
      await getCaptainDurationOnToday();
    });
  }

  void stopTimer() {
    print('Stopping timer');
    timer?.cancel();
  }

  @override
  void onInit() async {
    addToken();
    getPaymentToday();
    startPeriodicExecution();
    super.onInit();
  }

  addToken() async {
    await CRUD().post(link: AppLink.addTokensDriver, payload: {
      'token': box.read(BoxName.tokenDriver),
      'captain_id': box.read(BoxName.driverID).toString()
    }).then((value) => print('Token Added'));
    box.write(BoxName.statusDriverLocation, 'off');
  }

  getPaymentToday() async {
    var res = await CRUD().get(
        link: AppLink.getDriverpaymentToday,
        payload: {'driverID': box.read(BoxName.driverID).toString()});
    data = jsonDecode(res);
    totalMoneyToday = data['message'][0]['total_amount'];
    update();
  }

  Future<void> getCaptainDurationOnToday() async {
    var res = await CRUD().get(
        link: AppLink.getTotalDriverDurationToday,
        payload: {'driver_id': box.read(BoxName.driverID).toString()});

    data = jsonDecode(res);
    totalDurationToday = data['message'][0]['total_duration'];
    update();
  }

  @override
  void dispose() {
    activeTimer?.cancel();
    stopTimer();
    super.dispose();
  }
}
