"use client";
import { canAddVolunteerRole, isRoleCapacityWithinTotal } from "../roleCapacity";

import { useCallback, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { getRolesOfOpportunity } from "@/features/opportunities/services/roles";
import { getOpportunityById } from "@/features/opportunities/services/opportunities";
import { toNumber } from "@/lib/helpers";

/** Roles may leave unallocated seats; only an aggregate above capacity is invalid. */
export function useOpportunityRoles({
  opportunityId,
  authToken,
  openRoleModal,
  setMismatchChecker,
  shouldBlockNavigation,
}: {
  opportunityId: string;
  authToken?: string;
  /** Reopens this dialog when a blocked navigation is attempted. */
  openRoleModal: () => void;
  setMismatchChecker?: (utils: {
    checkParticipantsMismatch: () => boolean;
  }) => void;
  shouldBlockNavigation: boolean;
}) {
  const {
    data: roles,
    isLoading: rolesLoading,
    isError: rolesFailed,
    error: rolesError,
    refetch,
  } = useQuery({
    queryKey: ["opportunity-roles", opportunityId],
    queryFn: () => getRolesOfOpportunity({ opportunity_id: opportunityId }),
    enabled: Boolean(authToken),
    refetchOnMount: "always",
  });

  const {
    data: opportunityData,
    isLoading: opportunityLoading,
    isError: opportunityFailed,
    error: opportunityError,
    refetch: refetchOpportunity,
  } = useQuery({
    queryKey: ["opportunity-details", opportunityId],
    queryFn: () => getOpportunityById(opportunityId),
    enabled: Boolean(opportunityId),
    refetchOnMount: "always",
  });

  // Calculate total participants from roles. The API names this field
  // `participants_needed` on the role object itself (confirmed against a
  // live `/volunteer-opportunity-roles/` response) — not `total_participants_needed`.
  const totalRoleParticipants =
    roles?.data?.reduce(
      /* The element type comes from `getRolesOfOpportunity`, which is now
       typed — the annotation only hid which field the sum reads. */
    (sum, role) => sum + toNumber(role.participants_needed),
      0
    ) || 0;

  const opportunityParticipants = toNumber(
    opportunityData?.data?.participants_needed
  );
  const hasValidParticipants =
    isRoleCapacityWithinTotal(opportunityParticipants, totalRoleParticipants);

  const canAddRole = canAddVolunteerRole(opportunityParticipants, totalRoleParticipants);

  const participantsStillNeeded = Math.max(
    opportunityParticipants - totalRoleParticipants,
    0
  );

  // Shared validation function
  const shouldPreventAction = useCallback(() => {
    if (!shouldBlockNavigation || !roles?.data?.length) return false;
    return !hasValidParticipants;
  }, [shouldBlockNavigation, roles?.data, hasValidParticipants]);

  // Warn on tab close / reload while the roles don't add up.
  //
  // `beforeunload` only covers leaving the document. In-app navigation is
  // guarded by the `setMismatchChecker` callback the parent calls instead —
  // see the note on the hook above for why a router-level blocker is not
  // available.
  useEffect(() => {
    const handleBeforeUnload = () => {
      if (shouldPreventAction()) {
        openRoleModal();
        return "";
      }
    };

    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => window.removeEventListener("beforeunload", handleBeforeUnload);
  }, [shouldPreventAction, openRoleModal]);

  // Provide mismatch checker to the parent (VolunteerList / VolunteerForm)
  useEffect(() => {
    setMismatchChecker?.({
      checkParticipantsMismatch: () => shouldPreventAction(),
    });
  }, [setMismatchChecker, shouldPreventAction]);

  return {
    hasValidParticipants,
    canAddRole,
    roles,
    rolesLoading,
    refetch,
    opportunityLoading,
    /** Either read failing: not an empty roles table / zero capacity (p.37). */
    loadError: rolesFailed ? rolesError : opportunityFailed ? opportunityError : null,
    retryLoad: () => { void refetch(); void refetchOpportunity(); },
    participantsStillNeeded,
    shouldPreventAction,
  };
}
