"use client";

import { useClock } from "@/hooks/useClock";
import { canExcludeRegistration } from "../registrationManagementPolicy";
import { developmentAttendanceOpensAt } from "../developmentAttendanceWindow";
import { opportunityEndsAt } from "@/features/shared/clientReviewPolicy";
import moment from "moment";
import { getCheckInWindow } from "@/features/opportunities/checkInWindow";
import { type LearnServeRegisterListState } from "./learnServeRegisterListTypes";

/**
 * Whether the organizer may mark someone present right now: inside the
 * backend's check-in window (72h past the end by default, admin-adjustable)
 * and not before the final-day session start, which is when the server starts
 * accepting it. Without a schedule to read, the start of the last day.
 */
export function canMarkDevelopmentAttendance(
  navState: LearnServeRegisterListState | null | undefined,
  now: moment.Moment = moment()
): boolean {
  const checkInWindow = getCheckInWindow(navState, now);
  const opensAt = developmentAttendanceOpensAt(navState) ?? opportunityEndsAt(navState)?.clone().startOf("day") ?? null;
  return checkInWindow.requiresCheckIn && checkInWindow.isOpen && (opensAt ? now.isSameOrAfter(opensAt) : false);
}

/**
 * When the organizer may mark attendance, and when they may still remove a
 * registration.
 *
 * The check-in window is the backend's to define, so it is read from the
 * payload rather than recomputed. All four development types require actual
 * presence.
 */
export function useLearnServeCheckInWindow(
  navState: LearnServeRegisterListState | null
) {
  const clock = useClock(1000);
  const now = moment(clock);
  const checkInWindow = getCheckInWindow(navState, now);

  return {
    checkInWindow,
    canMarkAttendance: canMarkDevelopmentAttendance(navState, now),
    // Delete: visible always, disabled after start_date begins (strict after)
    isAfterAttendanceDeadline: !canExcludeRegistration(navState, now),
  };
}
