"use client";

import moment from "moment";
import { useClock } from "@/hooks/useClock";
import { useMemo } from "react";
import { getCheckInWindow } from "@/features/opportunities/checkInWindow";
import { NAV_STATE_KEYS } from "@/lib/navigationState";
import { awaitsApproval, type VolunteerListState } from "./volunteerListHelpers";
import { useNavState } from "@/hooks/useNavState";

/**
 * The opportunity this screen is about, and everything derived from it.
 *
 * It arrives through `NAV_STATE_KEYS.registerList` rather than the URL, so
 * `null` (not yet read) is a distinct state from `{}` (nothing was stashed) and
 * the screen must not decide anything until the first has passed.
 */
export function useVolunteerListNavState() {
  const clock = useClock(1000);
  const navState = useNavState<VolunteerListState>(
    NAV_STATE_KEYS.registerList
  );

  /**
   * The backend owns the check-in deadline (72h by default, admin-adjustable),
   * so the window is derived from its fields rather than recomputed here.
   * `manual_tracking` was already resolved upstream; the window re-checks it so
   * the controls lock the moment the deadline passes without a page reload.
   */
  const checkInWindow = getCheckInWindow(navState, moment(clock));
  const awaitingApproval = awaitsApproval(navState?.approval_status);

  const schedule = useMemo(
    () => ({
      start_time: navState?.start_time,
      end_time: navState?.end_time,
      time_slots: navState?.time_slots,
    }),
    [navState]
  );

  return {
    navState,
    opportunityId: navState?.id,
    opportunity_status: navState?.opportunity_status,
    /*
     * BE-69 — a volunteer granted «إذن تحضير» reaches this screen too, and does
     * the same work on it. Granting the permission on is the one thing that
     * stays with the organizer, so the button is gated on `is_creator` rather
     * than on `can_manage_attendance`.
     */
    isCreator: navState?.is_creator === true,
    checkInWindow,
    // Manual check-in is offered only while the window is genuinely open, and
    // never on an opportunity still awaiting (or refused) approval.
    manual_tracking: Boolean(navState && checkInWindow.isOpen && !awaitingApproval),
    awaitingApproval,
    opportunity_start_date: navState?.start_date,
    opportunity_end_date: navState?.end_date,
    opportunity_start_time: navState?.start_time,
    opportunity_end_time: navState?.end_time,
    participants_needed: navState?.participants_needed,
    schedule,
  };
}
