import 'dart:convert';

import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.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 = {};
  bool isLoading = true;
  String totalMoneyToday = '0';
  String totalMoneyInSEFER = '0';
  String totalDurationToday = '0';
  Timer? timer;
  bool mapType = false;
  bool mapTrafficON = false;
  double widthMapTypeAndTraffic = 50;
// Inject the LocationController class
  final locationController = Get.put(LocationController());
  String formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, "0");
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${duration.inHours}:$twoDigitMinutes:$twoDigitSeconds";
  }

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

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

  void changeMapType() {
    mapType = !mapType;
    // heightButtomSheetShown = isButtomSheetShown == true ? 240 : 0;
    update();
  }

  void changeMapTraffic() {
    mapTrafficON = !mapTrafficON;
    update();
  }

  GoogleMapController? mapHomeCaptaiController;
  void onMapCreated(GoogleMapController controller) {
    mapHomeCaptaiController = controller;
    controller.getVisibleRegion();
    controller.animateCamera(
      CameraUpdate.newLatLng(locationController.myLocation),
    );
    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();
    onButtonSelected();
    getPaymentToday();
    getAllPayment();
    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]['todayAmount'];

    update();
  }

  getAllPayment() async {
    var res = await CRUD().get(
        link: AppLink.getAllPayment,
        payload: {'driverID': box.read(BoxName.driverID).toString()});
    data = jsonDecode(res);

    totalMoneyInSEFER = 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();
  }
}
