import 'dart:async';

import 'package:SEFER/constant/table_names.dart';
import 'package:SEFER/controller/home/captin/map_driver_controller.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:SEFER/constant/box_name.dart';
import 'package:SEFER/constant/links.dart';
import 'package:SEFER/controller/functions/crud.dart';
import 'package:SEFER/controller/home/payment/captain_wallet_controller.dart';
import 'package:SEFER/main.dart';
import 'package:permission_handler/permission_handler.dart';

// LocationController.dart
class LocationController extends GetxController {
  LocationData? _currentLocation;
  late Location location;
  bool isLoading = false;
  bool isActive = false;
  late LatLng myLocation;
  late double heading;
  late double accuracy;
  late double latitude;
  late double longitude;
  late DateTime time;
  late double speed;
  late double speedAccuracy;
  late double headingAccuracy;
  String totalPoints = '0';
  LocationData? get currentLocation => _currentLocation;
  Timer? _locationTimer;

  @override
  void onInit() async {
    super.onInit();

    requestLocationPermission();

    location = Location();
    getLocation();
    // startLocationUpdates();

    totalPoints = Get.put(CaptainWalletController()).totalPoints;
  }

  Future<void> requestLocationPermission() async {
    if (box.read(BoxName.driverID) != null) {
      var status = await Permission.locationAlways.status;
      if (!status.isGranted) {
        await Permission.locationAlways.request();
      } else {
        var status = await Permission.locationWhenInUse.status;
        if (!status.isGranted) {
          await Permission.locationWhenInUse.request();
        }
      }
    }
  }

  Future<void> startLocationUpdates() async {
    if (box.read(BoxName.driverID) != null) {
      _locationTimer =
          Timer.periodic(const Duration(seconds: 5), (timer) async {
        try {
          totalPoints = Get.find<CaptainWalletController>().totalPoints;

          // if (isActive) {
          if (double.parse(totalPoints) > -300) {
            print('total point is $totalPoints');

            await getLocation();
            if (box.read(BoxName.driverID) != null) {
              await CRUD()
                  .post(link: AppLink.addCarsLocationByPassenger, payload: {
                'driver_id': box.read(BoxName.driverID).toString(),
                'latitude': myLocation.latitude.toString(),
                'longitude': myLocation.longitude.toString(),
                'heading': heading.toString(),
                'speed': speed.toString(),
                'status': box.read(BoxName.statusDriverLocation).toString()
              });
              if (Get.find<MapDriverController>().rideId == null) {
                await sql.insertData({
                  'driver_id': box.read(BoxName.driverID),
                  'latitude': myLocation.latitude.toString(),
                  'longitude': myLocation.longitude.toString(),
                  'created_at': DateTime.now().toString(),
                }, TableName.carLocations);
              } else {
                await sql.insertData({
                  'order_id': Get.find<MapDriverController>().rideId,
                  'created_at': DateTime.now().toString(),
                  'lat': myLocation.latitude.toString(),
                  'lng': myLocation.longitude.toString(),
                }, TableName.rideLocation);
              }
            }

            //
          }

          // }
        } catch (e) {
          // Handle the error gracefully
          print('Error during location updates: $e');
        }
      });
    }
  }

  void stopLocationUpdates() {
    _locationTimer?.cancel();
  }

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

    // Get the current location
    LocationData _locationData = await location.getLocation();
    myLocation = LatLng(_locationData.latitude!, _locationData.longitude!);

    accuracy = _locationData.accuracy!;
    latitude = _locationData.latitude!;
    longitude = _locationData.longitude!;
    heading = _locationData.heading!;
    speed = _locationData.speed!;
    speedAccuracy = _locationData.speedAccuracy!;
    headingAccuracy = _locationData.headingAccuracy!;

    // Print location details
    // print('myLocation: $myLocation');
    // print('Accuracy: $accuracy');
    // print('Latitude: $latitude');
    // print('Longitude: $longitude');
    // print('heading: $heading');
    // print('speed: $speed');
    // print('speedAccuracy: $speedAccuracy');
    // print('headingAccuracy: $headingAccuracy');

    isLoading = false;
    update();
  }
}
