import 'dart:async';

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationUtilities {
  static void havePermission(Function(bool) callback) {
    Geolocator.checkPermission().then((value) async {
      if (value == LocationPermission.denied || value == LocationPermission.deniedForever) {
        value = await Geolocator.requestPermission();
        callback(![LocationPermission.denied, LocationPermission.deniedForever].contains(value));
      } else {
        callback(true);
      }
    });
  }

  static void isEnabled(Function(bool) callback) {
    Geolocator.isLocationServiceEnabled().then((value) => callback(value));
  }

  static Future<bool> isEnabledAsync() async {
    return await Geolocator.isLocationServiceEnabled();
  }

  static Future<bool> havePermissionAsync() async {
    LocationPermission permission = await Geolocator.checkPermission();

    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
    }

    return permission == LocationPermission.always ||
        permission == LocationPermission.whileInUse;
  }

  static bool _listeningSettingChange = true;

  static void listenGPS({bool change = true, Function(bool)? onChange}) async {
    _listeningSettingChange = change;
    if (change == false) return;

    Future.doWhile(() async {
      await Future.delayed(const Duration(milliseconds: 1000));
      var enable = await Geolocator.isLocationServiceEnabled();
      onChange!(enable);
      return _listeningSettingChange;
    });
  }

  static void locationFun(Function(bool) completion, BuildContext context) {
    Permission.location.isGranted.then((isGranted) {
      if (!isGranted) {
        Permission.location.request().then((granted) {
          completion(granted == PermissionStatus.granted);
        });
      }
      completion(isGranted);
    });
  }
  static Future<void> getCurrentLocation(
      Function(Position position, bool isMocked) callback,
      Function(String error) errorCallBack,
      BuildContext context,
      ) async {
    debugPrint("📍 Fetching current location...");

    try {
      final position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high,
        timeLimit: const Duration(seconds: 10),
      );
      debugPrint("✅ Location: ${position.latitude}, ${position.longitude}");

      callback(position, position.isMocked);
    } catch (e) {
      debugPrint("❌ Primary location failed: $e");
      try {
        final lastPosition = await Geolocator.getLastKnownPosition();
        if (lastPosition != null) {
          debugPrint("⚠️ Using last known location");
          callback(lastPosition, lastPosition.isMocked);
          return;
        }
      } catch (fallbackError) {
        debugPrint("❌ Fallback failed: $fallbackError");
      }
      String message = "Unable to determine your location";
      final error = e.toString().toLowerCase();
      if (error.contains("timeout")) {
        message = "Location request timed out. Please try again.";
      } else if (error.contains("denied")) {
        message = "Location permission denied.";
      } else if (error.contains("disabled")) {
        message = "Location services are disabled.";
      }
      errorCallBack(message);
    }
  }

  // static void getCurrentLocation(Function(Position position, bool isMocked) callback, Function errorCallBack, BuildContext context) {
  //   Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.medium, timeLimit: const Duration(seconds: 5)).then((position) {
  //     bool isMocked = position.isMocked;
  //     callback(position, isMocked);
  //   }).catchError((err) {
  //     errorCallBack();
  //   });
  //   // return;
  //   // Permission.location.isGranted.then((isGranted) {
  //   //   if (!isGranted) {
  //   //     Permission.location.request().then((granted) {
  //   //       print("granted:$granted");
  //   //       if (granted == PermissionStatus.granted) {
  //   //         Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.medium, timeLimit: const Duration(seconds: 5)).then((position) {
  //   //           bool isMocked = position.isMocked;
  //   //           callback(position, isMocked);
  //   //         }).catchError((err) {
  //   //           print("getCurrentPositionError:$err");
  //   //           errorCallBack();
  //   //         });
  //   //       } else {
  //   //         errorCallBack();
  //   //       }
  //   //     });
  //   //   } else {
  //   //     Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.medium, timeLimit: const Duration(seconds: 5)).then((position) {
  //   //       bool isMocked = position.isMocked;
  //   //       callback(position, isMocked);
  //   //     }).catchError((err) {
  //   //       print("getCurrentPositionError:$err");
  //   //       errorCallBack();
  //   //     });
  //   //   }
  //   // });
  //   //
  //   // // Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.medium, timeLimit: const Duration(seconds: 5)).then((position) {
  //   // //   bool isMocked = position.isMocked;
  //   // //   callback(position, isMocked);
  //   // // }).catchError((err) {
  //   // //   print("getCurrentPositionError:$err");
  //   // //   errorCallBack();
  //   // // });
  //   //
  //   // // locationFun((granted) {
  //   // //   if (granted) {
  //   // //     Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.medium, timeLimit: const Duration(seconds: 5)).then((value) {
  //   // //       done(value);
  //   // //     }).catchError((err) {
  //   // //       print("getCurrentPositionError:$err");
  //   // //       errorCallBack();
  //   // //     });
  //   // //   } else {
  //   // //     // AppPermissions
  //   // //   }
  //   // // }, context);
  // }
}
