"use client";

import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  getMyAttendanceScans,
  type MyAttendanceScanRecord,
} from "@/features/opportunities/services/selfCheckIn";
import { isApiSuccess } from "@/lib/api/errors";
import { useClock } from "@/hooks/useClock";
import { isLiveScanWindow } from "../liveScanWindow";

/**
 * What the navbar scanner needs to know about one live session — the kind
 * (volunteering and development scan through different endpoints) and, for
 * volunteering, whether the scan must carry the device position (BE-101).
 */
export interface LiveAttendanceOpportunity {
  id: number;
  opportunity_type: MyAttendanceScanRecord["opportunity_type"];
  title_en: string | null;
  title_ar: string | null;
  requires_attendance_location?: boolean;
}

export type LiveScanKind = "volunteer" | "learn_serve";

export interface LiveAttendanceScan {
  kind: LiveScanKind;
  opportunity: LiveAttendanceOpportunity;
}

/** The query key, so a recorded scan can refresh the button. */
export const LIVE_ATTENDANCE_SCANS_KEY = ["live-attendance-scans"] as const;

/** How often the list is re-read — a session can open while the tab sits idle. */
const REFETCH_MS = 2 * 60_000;
/** How often the open/close times are re-checked against the clock. */
const TICK_MS = 30_000;

/**
 * The sessions this participant can scan into right now — volunteering and
 * development opportunities alike, in this one or any other they registered
 * for.
 *
 * Read from `GET /my-attendance-scans/` (BE-78 A). This used to be derived on
 * the client from `/list-user-opportunities/?opportunity_status=inprogress`
 * plus local window arithmetic, which missed the hour **before** a session
 * (its status is still "upcoming" then) and knew nothing of a development
 * opportunity's stable code (BE-119). The endpoint applies the same gates the
 * scan endpoints enforce: it leaves out organizers, events, an already-recorded
 * development presence, and a volunteering day whose arrival and departure are
 * both recorded. Legacy deployments still exclude some development types;
 * BE-192 removes that exclusion rather than fabricating eligible rows here.
 *
 * Each row carries `scan_opens_at` / `scan_closes_at`, so between refetches
 * the button still appears and disappears on time.
 */
export function useLiveAttendanceScans(enabled: boolean) {
  const clock = useClock(TICK_MS);

  const { data } = useQuery({
    queryKey: LIVE_ATTENDANCE_SCANS_KEY,
    queryFn: getMyAttendanceScans,
    enabled,
    refetchInterval: enabled ? REFETCH_MS : false,
    refetchOnWindowFocus: true,
  });

  return useMemo<LiveAttendanceScan[]>(() => {
    if (!data || !isApiSuccess(data) || !Array.isArray(data.data)) return [];
    return data.data
      .filter((row) => isLiveScanWindow(row, clock))
      .map((row) => ({
        kind: row.opportunity_type === "learn_serve_opportunity" ? "learn_serve" : "volunteer",
        opportunity: {
          id: row.opportunity_id,
          opportunity_type: row.opportunity_type,
          title_en: row.title_en,
          title_ar: row.title_ar,
          requires_attendance_location: row.requires_attendance_location,
        },
      }));
  }, [data, clock]);
}
