import {
  Alert,
  Linking,
  PermissionsAndroid,
  ToastAndroid,
  Platform,
} from "react-native";
import React, { useCallback, useEffect, useRef, useState } from "react";
import Geolocation from "react-native-geolocation-service";

import Database from "../../../../Components/common/Database";
import { render } from "@testing-library/react-native";
import { View } from "react-native";
import { async } from "validate.js";

let realm = Database.getRealm();
const updateLocation = (position) => {
  // Saving data in realm
  realm.write(() => {
    realm.delete(realm.objects("PILocation"));
    realm.create("PILocation", {
      lat: position?.coords?.latitude.toString().substring(0, 10),
      long: position?.coords?.longitude.toString().substring(0, 10),
    });
  });
  var PILocation = realm.objects("PILocation");
  console.log("____Location_____", PILocation);
};

const displayError = (error, setShowError) => {
  if (
    error.code === 2 &&
    error.message.indexOf("No location provider available") !== -1
  ) {
    locationAlert(setShowError);
  }
  setShowError(true);
  // Alert.alert(`Code ${error.code}`, ""+error.message);
  console.log("____Location_____", error);
};

const locationAlert = (setShowError) => {
  Alert.alert(
    "Location required!",
    "To smoothen your pre-inspection process we recommend you to enable device location.",
    [
      {
        text: "Ok",
        onPress: () => {
          if (Platform.OS === "ios") {
            Linking.canOpenURL("app-settings:")
              .then((supported) => {
                if (!supported) {
                  Alert.alert("Unable to open settings");
                } else {
                  return Linking.openURL("app-settings:");
                }
              })
              .catch((err) => {
                Alert.alert("Unable to open settings");
              });
          } else {
            Linking.openSettings().catch(() => {
              Alert.alert("Unable to open settings");
            });
          }
          setShowError(true);
        },
      },
    ]
  );
};

export default function GetLocation() {
  const watchId = useRef(null);
  const [showError, setShowError] = useState(true);

  useEffect(() => {
    return () => {
      removeLocationUpdates();
    };
  }, [removeLocationUpdates]);

  const removeLocationUpdates = useCallback(() => {
    if (watchId.current !== null) {
      stopForegroundService();
      Geolocation.clearWatch(watchId.current);
      watchId.current = null;
    }
  }, [stopForegroundService]);

  const stopForegroundService = useCallback(() => {
    // const VIForegroundService = require("@voximplant/react-native-foreground-service");
    // VIForegroundService.stopService().catch((err) => err);
  }, []);

  const goAsync = async () => {
    const hasPermission = await hasLocationPermission();

    if (!hasPermission) {
      return;
    }

    if (Platform.OS === "android") {
      // await startForegroundService();
    }

    const options = {
      accuracy: {
        android: "balanced",
        ios: "best",
      },
      enableHighAccuracy: true,
      timeout: 15000,
      maximumAge: 10000,
      distanceFilter: 50,
      forceRequestLocation: true,
      forceLocationManager: true,
      showLocationDialog: true,
    };
    watchId.current = Geolocation.watchPosition(
      (position) => {
        updateLocation(position);
      },
      (error) => {
        // setLocation(null);
        if (showError) {
          setShowError(false);
          displayError(error, setShowError);
        }
      },
      options
    );

    // Geolocation.getCurrentPosition(
    //   (position) => {
    //     updateLocation(position);
    //   },
    //   (error) => {
    //     displayError(error);
    //   },
    //   options
    // );
  };
  goAsync();
  return null; // render nothing
}

const startForegroundService = async () => {
  if (Platform.Version >= 26) {
    const VIForegroundService = require("@voximplant/react-native-foreground-service");
    await VIForegroundService.createNotificationChannel({
      id: "locationChannel",
      name: "Digit Preinspection",
      description: "Tracking location updates",
      enableVibration: false,
    });
  }

  return VIForegroundService.startService({
    channelId: "locationChannel",
    id: 420,
    title: "Digit Preinspection",
    text: "Tracking location updates",
    icon: "ic_launcher",
  });
};

const hasLocationPermission = async () => {
  if (Platform.OS === "ios") {
    const hasPermission = await hasPermissionIOS();
    return hasPermission;
  }

  if (Platform.OS === "android" && Platform.Version < 23) {
    return true;
  }

  const hasPermission = await PermissionsAndroid.check(
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
  );

  if (hasPermission) {
    return true;
  }

  const status = await PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
  );

  if (status === PermissionsAndroid.RESULTS.GRANTED) {
    return true;
  }

  if (status === PermissionsAndroid.RESULTS.DENIED) {
    ToastAndroid.show(
      "Location permission denied. Can not proceed.",
      ToastAndroid.LONG
    );
  } else if (status === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
    ToastAndroid.show(
      "Location permission revoked. Can not proceed.",
      ToastAndroid.LONG
    );
  }

  return false;
};

const hasPermissionIOS = async () => {
  const openSetting = () => {
    locationAlert();
  };
  const status = await Geolocation.requestAuthorization("whenInUse");

  if (status === "granted") {
    return true;
  }

  if (status === "denied") {
    Alert.alert("Location permission denied");
  }

  if (status === "disabled") {
    Alert.alert(`Turn on Location Services to determine your location.`, "", [
      { text: "Go to Settings", onPress: openSetting },
      { text: "Don't Use Location", onPress: () => {} },
    ]);
  }

  return false;
};
