"use client";

import { canExcludeRegistration } from "../registrationManagementPolicy";
import { Button } from "@/components/ui/Button";
import { SponsorsClient } from "@/features/home";
import VolunteerListToolbar from "./VolunteerListToolbar";
import MissedCheckOutBanner from "./MissedCheckOutBanner";
import VolunteerListModals from "./VolunteerListModals";
import VolunteerListTableSection from "./VolunteerListTableSection";
import { useVolunteerListScreen } from "./useVolunteerListScreen";
import AttendancePermissionModal from "./AttendancePermissionModal";
import CertificatesStateError from "./CertificatesStateError";
import { isVolunteerListSourceMissing } from "./volunteer-event/volunteerListNavState";
import { type MissedCheckOutMeta, type VolunteerListState } from "./volunteerListHelpers";

export type { VolunteerListState };

export default function VolunteerList() {
  const screen = useVolunteerListScreen();
  const { t } = screen;

  if (isVolunteerListSourceMissing(screen.navState)) {
    return (
      <p role="alert" className="mx-auto max-w-xl border-t border-[#000] px-4 py-16 text-center text-primary-5">
        {t("COMMON.VOLUNTEER_LIST_OPEN_FROM_OPPORTUNITY")}
      </p>
    );
  }

  return (
    <>

      <VolunteerListModals
        opportunityId={screen.opportunityId}
        filterOpen={screen.open}
        setFilterOpen={screen.setOpen}
        filters={screen.filters}
        onApplyFilters={screen.handleFilterChange}
        onClearFilters={() => screen.setFilters({ roles: [] })}
        roleModalState={screen.roleModalState && !screen.roleDisabled}
        onRoleModalClose={screen.handleRoleModalClose}
        onCloseRoleModal={screen.closeRoleModal}
        rolesRefetch={screen.teamsAndRoles.rolesRefetch}
        setMismatchChecker={screen.setRoleModalRef}
        showMismatchModal={screen.showMismatchModal}
        setShowMismatchModal={screen.setShowMismatchModal}
        pendingUndo={screen.attendance.pendingUndo}
        onCloseUndo={() => screen.attendance.setPendingUndo(null)}
        onConfirmUndo={screen.attendance.handleConfirmUndo}
        isConfirmingUndo={screen.attendance.isUndoingAttendance}
        showVolunteersModal={screen.showVolunteersModal && screen.isCreator && !screen.opportunityEnded}
        setShowVolunteersModal={screen.setShowVolunteersModal}
        showDeleteModal={screen.showDeleteModal && screen.isCreator && canExcludeRegistration(screen.navState)}
        setShowDeleteModal={screen.setShowDeleteModal}
        deletingVolunteerId={screen.deletingVolunteerId}
        onListChanged={screen.list.resetAndRefetchRegistrations}
      />

      <div className="border-t border-[#000]">
        <div className="2xl:w-[75%] laptopmain:w-[83%] laptop:w-[78%] laptopitm:w-[85%] lg:w-[90%] md:w-[85%] w-[90%] 2xl:py-[40px] laptopmain:py-[50px] laptop:py-[40px] lg:py-[40px] mobilescreen:py-[40px] py-[40px] mx-auto relative">
          <VolunteerListToolbar
            opportunity_start_date={screen.opportunity_start_date}
            opportunity_end_date={screen.opportunity_end_date}
            selectedDate={screen.attendance.selectedDate}
            effectiveEndDate={screen.attendance.effectiveEndDate}
            onDateChange={(date) => screen.attendance.setSelectedDate(date)}
            onOpenRoleModal={screen.openRoleModal}
            roleDisabled={screen.roleDisabled}
            attendancePermissionDisabled={screen.attendancePermissionDisabled}
            onOpenFilterModal={() => screen.setOpen(true)}
            onSearchChange={(value) => screen.list.setSearchQuery(value)}
            isSearching={screen.list.isSearching}
            onOpenAddVolunteer={() => screen.setShowVolunteersModal(true)}
            addVolunteerDisabled={
              !screen.isCreator || screen.isParticipantsFull ||
              screen.opportunityEnded || screen.awaitingApproval
            }
            onSendCertificates={screen.handleSendCertificates}
            sendCertificatesDisabled={
              !screen.isCreator ||
              !screen.opportunityEnded ||
              !screen.checkInWindow.isOpen ||
              screen.sendCertificatesMutation.isPending ||
              screen.certificatesNeedAttendee ||
              !screen.certificates.needsSending
            }
            sendCertificatesTitle={
              !screen.opportunityEnded
                ? screen.t("COMMON.CERTIFICATES_AFTER_END")
                : screen.certificatesNeedAttendee
                ? screen.t("COMMON.CERTIFICATES_NEED_ATTENDEE")
                : screen.certificates.blockedReason === "load-failed"
                ? screen.t("COMMON.CERTIFICATES_STATE_LOAD_FAILED")
                : screen.certificates.blockedReason === "up-to-date"
                ? screen.t("COMMON.CERTIFICATES_UP_TO_DATE")
                : undefined
            }
            onDownloadSheet={screen.handleDownload}
            downloadDisabled={screen.allRegistrations.length === 0}
            onOpenAttendancePermission={
              screen.isCreator
                ? () => screen.setShowAttendancePermission(true)
                : undefined
            }
            checkInWindow={screen.checkInWindow}
          />

          {/* Only where it is what blocks Send (A15): ended, window open, someone attended. */}
          {screen.isCreator && screen.opportunityEnded && screen.checkInWindow.isOpen && !screen.certificatesNeedAttendee && screen.certificates.blockedReason === "load-failed" && (
            <CertificatesStateError error={screen.certificates.error} onRetry={screen.certificates.retry} />
          )}
          {screen.isCreator && screen.certificates.note && (
            <p role="status" className="mb-4 text-end text-sm text-secondary-102">{screen.certificates.note}</p>
          )}
          {screen.isCreator && (
            <MissedCheckOutBanner
              registrations={screen.allRegistrations}
              canStillEdit={screen.checkInWindow.isOpen}
              meta={screen.list.registrations?.meta as MissedCheckOutMeta | undefined}
              listComplete={screen.listComplete}
            />
          )}

          {/* Mounted only while screen.open so it reopens in its initial state. */}
          {screen.showAttendancePermission && !screen.attendancePermissionDisabled && (
            <AttendancePermissionModal
              onClose={() => screen.setShowAttendancePermission(false)}
              opportunityId={screen.opportunityId}
            />
          )}

          <VolunteerListTableSection
            registrations={screen.allRegistrations}
            hasMoreRegistrations={screen.list.hasMoreRegistrations}
            loadMoreRegistrations={screen.list.loadMoreRegistrations}
            loadError={screen.list.loadError} onRetry={screen.list.retryRegistrations}
            manual_tracking={screen.manual_tracking}
            requiresCheckIn={screen.checkInWindow.requiresCheckIn}
            opportunity_start_date={screen.opportunity_start_date}
            opportunity_end_time={screen.opportunity_end_time}
            schedule={screen.schedule}
            exclusionSource={screen.navState ? { ...screen.navState, can_exclude: screen.isCreator } : null}
            roleDisabled={screen.roleDisabled}
            attendance={screen.attendance}
            teamsAndRoles={screen.teamsAndRoles}
            onRequestUnregister={(userId) => {
              screen.setDeletingVolunteerId(userId);
              screen.setShowDeleteModal(true);
            }}
          />

          <div
            className={`${
              screen.manual_tracking ? "flex flex-col" : "flex justify-center"
            } mx-auto py-12 mobilescreen:py-8 gap-7 items-center`}
          >
            {screen.manual_tracking && (
              <Button
                className="transition focus:outline-none text-center flex justify-center items-center gap-2 opacity-100 focus:ring-2 font-bold text-base 2xl:h-[48px] 2xl:w-[190px] rounded-[30px] 2xl:text-[20px] lg:text-[14px] laptop:w-[180px] lg:w-[150px] lg:h-[40px] laptop:rounded-[30px] laptop:h-[40px] laptopmain:h-[40px] xss:rounded-[20px] bg-white !text-primary-5 !w-[255px] !h-[48px] border border-primary-5"
                onClick={screen.attendance.handleMarkAttendanceClick}
                disabled={
                  screen.attendance.isMarkingAttendance ||
                  screen.attendance.selectedAttendance.length === 0 ||
                  !screen.checkInWindow.isOpen
                }
              >
                {t("COMMON.ATTENDED")}
              </Button>
            )}
          </div>
        </div>

        <div className="border-t border-[#000]/20 pt-12">
          <SponsorsClient />
        </div>
      </div>
    </>
  );
}
