"use client";

import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { getApiErrorMessages, isApiSuccess } from "@/lib/api/errors";
import {
  ATTENDANCE_LOCATION_LIVE,
  ScanPositionError,
  getRecentScanPosition,
  isLocationMissingError,
  isLocationRejectedError,
  requiresAttendanceLocation,
} from "@/features/opportunities/attendanceLocation";
import {
  isAttendanceAlreadyRecordedError,
  learnServeSelfScan,
  volunteerSelfScan,
} from "@/features/opportunities/services/selfCheckIn";
import {
  LIVE_ATTENDANCE_SCANS_KEY,
  type LiveAttendanceScan,
} from "@/features/opportunities/hooks/useLiveAttendanceScans";
import { useQueryClient } from "@tanstack/react-query";
import { useLanguageStore } from "@/store/languageStore";

/**
 * Everything that happens between tapping the navbar's scan button and a
 * recorded attendance.
 *
 * It is a surprising amount for one button, which is why it is not in the
 * button: a location fix may be required before the camera even opens, a code
 * may belong to either kind of opportunity so a volunteering scan falls back
 * to learn & serve, and the server may ask for a location the list payload did
 * not say was needed — in which case the fix is taken and the scan retried.
 * Which of those happened decides whether the camera stays up or closes.
 */
export function useAttendanceScanFlow(scans: LiveAttendanceScan[]) {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);

  const queryClient = useQueryClient();
  /* After a recorded scan: the button re-reads what is left to scan (a
     development opportunity is one scan ever), and an open detail page
     picks up its new attendance state. */
  const refreshAfterScan = () => {
    void queryClient.invalidateQueries({ queryKey: LIVE_ATTENDANCE_SCANS_KEY });
    void queryClient.invalidateQueries({ queryKey: ["learn-serve-opportunity"] });
    void queryClient.invalidateQueries({ queryKey: ["volunteer-opportunity"] });
  };

  const [scanning, setScanning] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [locating, setLocating] = useState(false);

  /** Is any of the live sessions a learn & serve one? */
  const mayBeLearnServe = scans.some((scan) => scan.kind === "learn_serve");
  const mayBeVolunteering = scans.some((scan) => scan.kind === "volunteer");
  /**
   * BE-101 — which code is about to be scanned is unknown here, so the fix is
   * taken whenever any live volunteering session asks for one.
   */
  const mayNeedLocation = scans.some(
    (scan) =>
      scan.kind === "volunteer" && requiresAttendanceLocation(scan.opportunity)
  );

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

  const openScanner = async () => {
    if (!mayNeedLocation) {
      setScanning(true);
      return;
    }
    setLocating(true);
    try {
      await getRecentScanPosition();
      setScanning(true);
    } catch (error) {
      toastPositionError(error);
    } finally {
      setLocating(false);
    }
  };

  /**
   * One volunteering scan. When the list payload didn't say the opportunity
   * checks location but the server asks for it anyway, the fix is taken and
   * the scan sent once more.
   */
  const scanVolunteering = async (code: string) => {
    const position = mayNeedLocation ? await getRecentScanPosition() : undefined;
    try {
      return await volunteerSelfScan({ code, ...position });
    } catch (error) {
      if (position || !ATTENDANCE_LOCATION_LIVE || !isLocationMissingError(error)) {
        throw error;
      }
      return volunteerSelfScan({ code, ...(await getRecentScanPosition()) });
    }
  };

  const handleScan = async (code: string) => {
    setSubmitting(true);
    try {
      if (mayBeVolunteering) {
        try {
          const response = await scanVolunteering(code);
          if (isApiSuccess(response)) {
            // One presence scan per day: there is no direction to report.
            toast.success(response.msg || t("COMMON.TOAST.ATTENDANCE_RECORDED"));
            setScanning(false);
            refreshAfterScan();
            return;
          }
          throw new Error("scan rejected");
        } catch (error) {
          // Only fall through when a learn & serve code is actually plausible;
          // otherwise this is a real failure and the volunteering error is the
          // one worth showing.
          // A location refusal means the code *was* a volunteering one, so
          // it is never retried as learn & serve — and so does a 409: the
          // code matched and today's attendance is already in.
          if (
            !mayBeLearnServe ||
            error instanceof ScanPositionError ||
            isLocationRejectedError(error) ||
            isAttendanceAlreadyRecordedError(error)
          ) {
            throw error;
          }
        }
      }

      const learnServeResponse = await learnServeSelfScan({ code });
      /* The server's own message: one scan for the whole course, so this is
         «تم تسجيل الحضور بنجاح» — kept verbatim rather than a fixed string so
         any later wording change on the backend reaches the participant. */
      toast.success(
        (learnServeResponse as { msg?: string } | undefined)?.msg ||
          t("COMMON.TOAST.ATTENDANCE_RECORDED")
      );
      setScanning(false);
      refreshAfterScan();
    } catch (error) {
      if (error instanceof ScanPositionError) {
        // No fix, no scan: close the camera and say why.
        toastPositionError(error);
        setScanning(false);
        return;
      }
      const messages = getApiErrorMessages(error, language);
      if (messages.length > 0) messages.forEach((m) => toast.error(m));
      else toast.error(t("COMMON.TOAST.SELF_SCAN_FAILED"));
      if (isAttendanceAlreadyRecordedError(error)) {
        // 409 — already recorded (today, or for the whole course). Nothing a
        // re-scan can change: close the camera and drop it from the live list.
        setScanning(false);
        refreshAfterScan();
        return;
      }
      /*
       * Rethrown so the camera stays up. From the navbar the likeliest failure
       * is pointing at the wrong sheet entirely — a second attempt at another
       * code fixes it, reopening the dialog does not. The out-of-window 400
       * («المسح متاح أثناء الجلسة فقط») is shown as the server sent it.
       */
      throw error;
    } finally {
      setSubmitting(false);
    }
  };

  return {
    scanning,
    setScanning,
    submitting,
    locating,
    openScanner,
    handleScan,
  };
}
