"use client";

import { useCallback, useEffect, useState } from "react";

export interface GeoReading {
  latitude: number;
  longitude: number;
  accuracy: number;
  timestamp: number;
}

/** "unknown" when the browser has no Permissions API (or it refused the query). */
export type LocationPermission = "unknown" | "prompt" | "granted" | "denied";

/**
 * "denied" = the browser/site blocked access; "unavailable" = permission is
 * fine but no fix came back (typically the phone's GPS/Location is off).
 */
export type LocationErrorCode = "denied" | "unavailable" | "timeout" | "unsupported";

export class LocationError extends Error {
  readonly code: LocationErrorCode;

  constructor(code: LocationErrorCode, message: string) {
    super(message);
    this.name = "LocationError";
    this.code = code;
  }
}

interface GeolocationState {
  status: "idle" | "loading" | "ready" | "error";
  reading: GeoReading | null;
  error: string | null;
  errorCode: LocationErrorCode | null;
  permission: LocationPermission;
}

/**
 * Never caches a reading across calls to `refresh` — the brief requires a
 * fresh GPS fix immediately before every capture, not a reused stale one.
 *
 * Also watches the site's location permission so the page can warn before
 * the employee takes a photo, and clears a "denied" error on its own once
 * they re-enable access in the browser settings and come back to the tab.
 */
export function useGeolocation() {
  const [state, setState] = useState<GeolocationState>({
    status: "idle",
    reading: null,
    error: null,
    errorCode: null,
    permission: "unknown",
  });

  useEffect(() => {
    // Unsupported browsers are reported by `refresh` on the first capture.
    if (!("geolocation" in navigator) || !navigator.permissions?.query) return;

    let cancelled = false;
    let permissionStatus: PermissionStatus | null = null;

    const applyPermission = (permission: PermissionState) => {
      setState((current) => {
        const recovered = permission !== "denied" && current.errorCode === "denied";
        return recovered
          ? { ...current, permission, status: "idle", error: null, errorCode: null }
          : { ...current, permission };
      });
    };
    const onChange = () => permissionStatus && applyPermission(permissionStatus.state);
    // Not every browser fires `change` when the setting is flipped in
    // another screen, so re-query whenever the employee returns to the tab.
    const query = () =>
      navigator.permissions
        .query({ name: "geolocation" })
        .then((result) => {
          if (cancelled) return;
          if (permissionStatus !== result) {
            permissionStatus?.removeEventListener("change", onChange);
            permissionStatus = result;
            result.addEventListener("change", onChange);
          }
          applyPermission(result.state);
        })
        .catch(() => {
          // Permissions API exists but rejects "geolocation" — stay "unknown".
        });
    const onVisible = () => document.visibilityState === "visible" && query();

    query();
    document.addEventListener("visibilitychange", onVisible);
    return () => {
      cancelled = true;
      permissionStatus?.removeEventListener("change", onChange);
      document.removeEventListener("visibilitychange", onVisible);
    };
  }, []);

  const refresh = useCallback((): Promise<GeoReading> => {
    // Keep the previous error visible while retrying so the help panel
    // doesn't flicker away and back when the retry fails again.
    setState((current) => ({ ...current, status: "loading" }));

    return new Promise((resolve, reject) => {
      if (!("geolocation" in navigator)) {
        setState((current) => ({
          ...current,
          status: "error",
          reading: null,
          error: errorMessages.unsupported,
          errorCode: "unsupported",
        }));
        reject(new LocationError("unsupported", errorMessages.unsupported));
        return;
      }

      navigator.geolocation.getCurrentPosition(
        (position) => {
          const reading: GeoReading = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            accuracy: position.coords.accuracy,
            timestamp: position.timestamp,
          };
          setState({ status: "ready", reading, error: null, errorCode: null, permission: "granted" });
          resolve(reading);
        },
        (positionError) => {
          const code = errorCodeFor(positionError);
          setState((current) => ({
            ...current,
            status: "error",
            reading: null,
            error: errorMessages[code],
            errorCode: code,
            permission: code === "denied" ? "denied" : current.permission,
          }));
          reject(new LocationError(code, errorMessages[code]));
        },
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 },
      );
    });
  }, []);

  return { ...state, refresh };
}

const errorMessages: Record<LocationErrorCode, string> = {
  denied: "Izin lokasi ditolak. Aktifkan izin lokasi untuk melakukan absensi.",
  unavailable: "Lokasi tidak dapat dideteksi. Pastikan GPS/Lokasi di HP aktif, lalu coba lagi.",
  timeout: "Waktu permintaan lokasi habis. Coba lagi.",
  unsupported: "Perangkat/browser ini tidak mendukung geolocation.",
};

function errorCodeFor(error: GeolocationPositionError): LocationErrorCode {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      return "denied";
    case error.TIMEOUT:
      return "timeout";
    default:
      return "unavailable";
  }
}
