"use client";

import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { LIVE_ATTENDANCE_SCANS_KEY } from "@/features/opportunities/hooks/useLiveAttendanceScans";
import { toast } from "sonner";
import { isMobileAttendanceDevice } from "@/components/layout/attendanceScanDevice";
import { getApiErrorMessages } from "@/lib/api/errors";
import {
  ScanPositionError,
  getRecentScanPosition,
  requiresAttendanceLocation,
  type ScanPosition,
} from "@/features/opportunities/attendanceLocation";
import {
  isAttendanceAlreadyRecordedError,
  volunteerSelfScan,
} from "@/features/opportunities/services/selfCheckIn";

/**
 * The volunteer's own presence scan — one per day, no direction.
 *
 * Four rules live here and each one decides whether the camera stays up:
 *
 *  - **the location prompt comes before the camera** (BE-101), on the tap
 *    itself, so a volunteer who refuses it learns why now rather than after
 *    lining up the code;
 *  - **a missing position closes the camera** — no amount of re-scanning
 *    produces a fix;
 *  - **"already recorded" (409) closes it too**, and refreshes the page so the
 *    button gives way to "attended today";
 *  - **any other rejection keeps it up** — pointing at the wrong sheet is fixed
 *    by pointing somewhere else, which is why that one path rethrows. The
 *    server's message is shown as sent, including the out-of-window 400.
 */
export function useVolunteerSelfScan({
  data,
  language,
  t,
  onRecorded,
}: {
  data: { requires_attendance_location?: boolean | number | null };
  language: string;
  t: (key: string, options?: Record<string, unknown>) => string;
  onRecorded: () => void;
}) {
  const [open, setOpen] = useState(false);
  const [locating, setLocating] = useState(false);
  const queryClient = useQueryClient();
  /* The header scan button lists what is left to scan; without this it kept
     offering a completed day for up to its two-minute refetch. */
  const scanMutation = useMutation({
    mutationFn: volunteerSelfScan,
    onSettled: () => queryClient.invalidateQueries({ queryKey: LIVE_ATTENDANCE_SCANS_KEY }),
  });
  const needsLocation = requiresAttendanceLocation(data);

  const toastPositionError = (error: unknown) =>
    toast.error(
      t(
        error instanceof ScanPositionError
          ? error.messageKey
          : "COMMON.ATTENDANCE_LOCATION_UNAVAILABLE"
      )
    );

  const toastApiMessages = (error: unknown) => {
    const messages = getApiErrorMessages(error, language);
    if (messages.length > 0) messages.forEach((m) => toast.error(m));
    else toast.error(t("COMMON.TOAST.SELF_SCAN_FAILED"));
  };

  /*
   * BE-101 — the permission prompt comes before the camera, on the tap itself:
   * a volunteer who refuses it learns why now, not after lining up the code.
   */
  const openScanner = async () => {
    if (!isMobileAttendanceDevice(navigator)) {
      toast.info(t("COMMON.ATTENDANCE_SCAN_MOBILE_REQUIRED"), { duration: 7000 });
      return;
    }
    if (!needsLocation) {
      setOpen(true);
      return;
    }
    setLocating(true);
    try {
      await getRecentScanPosition();
      setOpen(true);
    } catch (error) {
      toastPositionError(error);
    } finally {
      setLocating(false);
    }
  };

  const handleScan = async (code: string) => {
    let position: ScanPosition | undefined;
    if (needsLocation) {
      try {
        position = await getRecentScanPosition();
      } catch (error) {
        // Closes the camera: no amount of re-scanning fixes a missing fix.
        toastPositionError(error);
        return;
      }
    }

    try {
      const response = await scanMutation.mutateAsync({ code, ...position });
      toast.success(response?.msg || t("COMMON.TOAST.ATTENDANCE_RECORDED"));
      onRecorded();
    } catch (error) {
      toastApiMessages(error);
      if (isAttendanceAlreadyRecordedError(error)) {
        // Closes the camera and re-reads `self_attendance`: today is done.
        onRecorded();
        return;
      }
      // Rethrown so the camera stays up: pointing at the wrong sheet is fixed
      // by pointing somewhere else, not by reopening the dialog.
      throw error;
    }
  };

  return {
    /** Whether the on-site radius applies — the hint text needs it too. */
    needsLocation,
    open,
    setOpen,
    locating,
    isPending: scanMutation.isPending,
    openScanner,
    handleScan,
  };
}
