"use client";

import { useState } from "react";
import { canManageVolunteerRoles } from "../registrationManagementPolicy";
import { hasOpportunityEnded } from "@/features/shared/clientReviewPolicy";
import { useTranslation } from "react-i18next";
import { useTeamsAndRoles } from "@/features/opportunities/hooks/useTeamsAndRoles";
import { useVolunteerAttendance } from "@/features/opportunities/hooks/useVolunteerAttendance";
import { toNumber } from "@/lib/helpers";
import { useRoleModalStore } from "@/store/roleModalStore";
import { useVolunteerListNavState } from "./useVolunteerListNavState";
import { useVolunteerRegistrationsList } from "./useVolunteerRegistrationsList";
import { useVolunteerListExports } from "./useVolunteerListExports";
import { useCertificatesOutdated } from "./useCertificatesOutdated";

/**
 * Everything the volunteering registrations screen needs, assembled.
 *
 * The screen wires together six hooks — the stashed opportunity, the paged
 * registrations, attendance, teams and roles, the exports, and a store-backed
 * role modal — plus nine pieces of dialog state. Assembling them here leaves the
 * component as markup, and is what lets the pieces be read one at a time.
 */
export function useVolunteerListScreen() {
  const { t } = useTranslation();

  const roleModalState = useRoleModalStore((s) => s.roleModalState);
  const openRoleModal = useRoleModalStore((s) => s.openRoleModal);
  const closeRoleModal = useRoleModalStore((s) => s.closeRoleModal);

  const {
    navState,
    opportunityId,
    opportunity_status,
    isCreator,
    checkInWindow,
    manual_tracking,
    opportunity_start_date,
    opportunity_end_date,
    opportunity_start_time,
    opportunity_end_time,
    participants_needed,
    schedule,
    awaitingApproval,
  } = useVolunteerListNavState();
  const [showAttendancePermission, setShowAttendancePermission] =
    useState(false);

  const [open, setOpen] = useState(false);
  const [showMismatchModal, setShowMismatchModal] = useState(false);
  const [roleModalRef, setRoleModalRef] = useState<{
    checkParticipantsMismatch: () => boolean;
  } | null>(null);

  const [filters, setFilters] = useState<{ roles?: number[] }>(
    {}
  );
  const [showVolunteersModal, setShowVolunteersModal] = useState(false);

  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deletingVolunteerId, setDeletingVolunteerId] = useState<number | null>(
    null
  );

  /*
   * The two hooks below need each other: the list must tell attendance about
   * each newly merged page (so "select all" stays in force across pages), and
   * attendance reads and writes the accumulated rows the list owns.
   *
   * The callback goes through a ref, assigned in an effect rather than during
   * render, which breaks the cycle without a render-time ref write. Safe here
   * because only pages *after* the first invoke it, and by then the effect has
   * run.
   */

  const list = useVolunteerRegistrationsList({
    opportunityId,
    roles: filters.roles,
    // "Select all" stays sticky across pages while the mode is on
  });
  const registrations = list.registrations;
  const allRegistrations = list.allRegistrations;
  const debouncedSearch = list.debouncedSearch;

  const attendance = useVolunteerAttendance({
    opportunityId,
    manual_tracking,
    opportunity_start_date,
    opportunity_end_date,
    opportunity_end_time,
    allRegistrations,
    patchRegistrations: list.patchRegistrations,
  });

  const roleDisabled = !opportunityId || !isCreator || !canManageVolunteerRoles(navState);
  const teamsAndRoles = useTeamsAndRoles({
    canManage: !roleDisabled,
    opportunityId,
    onUpdated: list.resetAndRefetchRegistrations,
  });

  const { handleDownload, handleSendCertificates, sendCertificatesMutation } =
    useVolunteerListExports({
      opportunityId,
      canSend: isCreator && hasOpportunityEnded(navState) && checkInWindow.isOpen,
      t,
      roles: filters.roles,
      debouncedSearch,
      manualTracking: manual_tracking,
      selectedDate: attendance.selectedDate,
    });

  const handleFilterChange = (newFilters: {

    roles?: string[];
  }) => {
    setFilters({
      roles: newFilters.roles ? newFilters.roles.map(Number) : undefined,
    });
    void list.resetAndRefetchRegistrations();
    setOpen(false);
  };

  const handleRoleModalClose = () => {
    if (roleModalRef?.checkParticipantsMismatch()) {
      setShowMismatchModal(true);
      return;
    }
    closeRoleModal();
  };

  const opportunityEnded = opportunity_status === "cancelled" || hasOpportunityEnded({
    ...schedule, start_date: opportunity_start_date, end_date: opportunity_end_date,
    start_time: opportunity_start_time, end_time: opportunity_end_time,
    opportunity_status,
  });
  const attendancePermissionDisabled = !opportunityId || !isCreator ||
    opportunityEnded;

  const registeredCount =
    registrations?.meta?.pagination?.total || allRegistrations.length || 0;
  const isParticipantsFull = Boolean(
    participants_needed && registeredCount >= toNumber(participants_needed)
  );

  /*
   * «زر إصدار الشهادات لا يتفعل إلا إذا تم تحضير شخص واحد على الأقل» (client,
   * 2026-10-10). `is_attended` on a row means "today", so the per-day
   * `attendances` records are what say "ever". The list is paged and can be
   * searched or filtered, so "nobody" is only claimed when every row is
   * loaded and unfiltered; otherwise the button is left to the server (BE-121).
   */
  const anyCheckedIn = allRegistrations.some((row) =>
    (row.attendances ?? []).some(
      (record) => Number(record.total_hours) > 0
    )
  );
  const listComplete =
    !list.isLoading &&
    !list.hasMoreRegistrations &&
    !list.debouncedSearch &&
    !(filters.roles && filters.roles.length > 0);
  const certificatesNeedAttendee = listComplete && !anyCheckedIn;
  const certificates = useCertificatesOutdated("volunteer", opportunityId);

  return {
    t,
    navState,
    opportunityId,
    opportunity_status,
    isCreator,
    checkInWindow,
    manual_tracking,
    opportunity_start_date,
    opportunity_end_date,
    opportunity_start_time,
    opportunity_end_time,
    schedule,
    showAttendancePermission,
    setShowAttendancePermission,
    open,
    setOpen,
    showMismatchModal,
    setShowMismatchModal,
    setRoleModalRef,
    filters,
    setFilters,
    showVolunteersModal,
    setShowVolunteersModal,
    showDeleteModal,
    setShowDeleteModal,
    deletingVolunteerId,
    setDeletingVolunteerId,
    list,
    allRegistrations,
    attendance,
    teamsAndRoles,
    roleModalState,
    closeRoleModal,
    openRoleModal: () => { if (!roleDisabled) openRoleModal(); },
    handleDownload,
    handleSendCertificates,
    sendCertificatesMutation,
    handleFilterChange,
    handleRoleModalClose,
    isParticipantsFull,
    opportunityEnded,
    awaitingApproval,
    roleDisabled,
    attendancePermissionDisabled,
    certificatesNeedAttendee,
    certificates,
    listComplete,
  };
}
