"use client";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { effectiveSelectedUsers } from "./registrationSelection";
import { Button } from "@/components/ui/Button";
import Loader from "@/components/ui/Loader";
import { SponsorsClient } from "@/features/home";
import { grantsCertificate, usesFursaCertificate, sendCertificatesBlockedReason } from "@/features/opportunities/learnServeCertificates";
import { useCertificatesOutdated } from "./useCertificatesOutdated";
import { NAV_STATE_KEYS } from "@/lib/navigationState";
import { useLanguageStore } from "@/store/languageStore";
import { type LearnServeRegisterListState } from "./learnServeRegisterListTypes";
import { buildRegisterListColumns } from "./learnServeRegisterListColumns";
import { useRegistrationSelection } from "./useRegistrationSelection";
import { useLearnServeRegistrationsList } from "./useLearnServeRegistrationsList";
import { useLearnServeRegisterListActions } from "./useLearnServeRegisterListActions";
import { useWindowWidth } from "@/hooks/useWindowWidth";
import RegisterListToolbar from "./RegisterListToolbar";
import RegisterListTable from "./RegisterListTable";
import DeleteRegistrationModal from "./DeleteRegistrationModal";
import { useLearnServeCheckInWindow } from "./useLearnServeCheckInWindow";
import { useNavState } from "@/hooks/useNavState";
import { useAuthStore } from "@/store/authStore";
import ParticipantsPayments from "./ParticipantsPayments";
import { paidRemovalBlock, registrationPerson } from "@/features/opportunities/registrationRow";

export type { LearnServeRegisterListState };

export default function RegisterListForLearnandServe() {
  const { t } = useTranslation();
  const isOrganization = useAuthStore((s) => s.user?.user_type) === "organization";
  const selectedLanguage = useLanguageStore((s) => s.language);
  const windowWidth = useWindowWidth();

  const navState = useNavState<LearnServeRegisterListState>(
    NAV_STATE_KEYS.registerList,
  );
  const opportunityId = navState?.id;
  const isPaidOpportunity = navState?.is_paid === true;

  const canGrantCertificates = grantsCertificate(navState?.learning_type_display) && usesFursaCertificate(navState?.certificate_type_display);
  const selection = useRegistrationSelection();
  const list = useLearnServeRegistrationsList({
    opportunityId,
    setSelection: selection.setSelection,
  });

  const { checkInWindow, canMarkAttendance, isAfterAttendanceDeadline } =
    useLearnServeCheckInWindow(navState);
  const certificates = useCertificatesOutdated("learn-serve", opportunityId, navState?.opportunity_status);

  const sendBlockedReason = sendCertificatesBlockedReason(
    certificates.opportunityStatus,
    {
      anyAttended: list.allRegisteredUsers.some((row) => row.is_attended === true),
      // Only sure "nobody" when the whole, unfiltered list is on screen.
      certain: !list.isLoading && !list.hasMore && !list.debouncedSearch,
    },
  );

  const selectedUsers = useMemo(
    () => effectiveSelectedUsers(selection.selection, list.allRegisteredUsers),
    [selection.selection, list.allRegisteredUsers]
  );
  const actions = useLearnServeRegisterListActions({
    opportunityId,
    t,
    selectedLanguage,
    debouncedSearch: list.debouncedSearch,
    selectedUsers,
    clearSelection: selection.clearSelection,
    setSelection: selection.setSelection,
    setAllRegisteredUsers: list.setAllRegisteredUsers,
    resetList: list.resetList,
    refetchRegistrations: list.refetchRegistrations,
    sendBlockedReason,
    canMarkAttendance,
    canSendCertificates: canGrantCertificates && checkInWindow.isOpen && certificates.needsSending,
  });

  const columns = buildRegisterListColumns({
    t,
    requiresCheckIn: checkInWindow.requiresCheckIn,
    rows: list.allRegisteredUsers,
    selectAll: selection.selectAll,
    onSelectAllChange: () =>
      selection.handleSelectAllChange(list.allRegisteredUsers),
  });

  // `navState === null` means the stashed payload has not been read yet.
  if (navState === null) return <Loader />;

  if (!opportunityId) {
    return (
      <div className="text-center py-8 text-gray-500">
        {t("COMMON.NO_OPPORTUNITY_ID")}
      </div>
    );
  }

  return (
    <div className="w-full 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">
        <RegisterListToolbar
          onSearchChange={list.setSearchQuery}
          isSearching={list.isSearching}
          checkInWindow={checkInWindow}
          canGrantCertificates={canGrantCertificates}
          sendBlockedReason={checkInWindow.isClosed ? "window-closed" : sendBlockedReason ?? certificates.blockedReason}
          certificatesNote={certificates.note}
          certificatesError={certificates.error}
          onRetryCertificates={certificates.retry}
          isSendingCertificates={actions.sendCertificatesMutation.isPending}
          onSendCertificates={actions.handleSendCertificates}
          onDownloadSheet={actions.handleDownloadSheet}
          hasRows={list.allRegisteredUsers.length > 0}
        />

        <div className="w-full">
          <RegisterListTable
            // Full-page loader only on the very first load, not on search refetches.
            showInitialLoader={
              list.showInitialLoader
            }
            columns={columns}
            rows={list.allRegisteredUsers}
            hasMore={list.hasMore}
            loadMore={list.loadMoreRegistrations}
            selectedLanguage={selectedLanguage}
            selectedUsers={selectedUsers}
            onToggle={(userId) =>
              selection.handleCheckboxChange(userId, list.allRegisteredUsers)
            }
            isAfterAttendanceDeadline={isAfterAttendanceDeadline}
            canMarkAttendance={canMarkAttendance}
            opportunityId={opportunityId} onAttendanceUndone={() => { list.resetList(); void list.refetchRegistrations(); }}
            loadError={list.loadError} onRetry={() => void list.refetchRegistrations()}
            deleteBlockedLabelFor={(row) => {
              const block = paidRemovalBlock(row);
              return block === "paid"
                ? t("COMMON.DELETE_REGISTRATION_PAID_BLOCKED")
                : block === "pending"
                  ? t("COMMON.DELETE_REGISTRATION_PAYMENT_PENDING")
                  : null;
            }}
            onDelete={(userId, userName) => {
              // Prevent opening delete modal after attendance deadline
              if (isAfterAttendanceDeadline) return;
              const row = list.allRegisteredUsers.find(
                (candidate) => String(registrationPerson(candidate).userId) === String(userId)
              );
              if (paidRemovalBlock(row)) return;
              actions.openDeleteModal(
                userId,
                userName,
                row?.is_attended === true || row?.is_certified === true
              );
            }}
            windowWidth={windowWidth}
          />
        </div>

        <div className="flex flex-col items-center gap-7 justify-center mx-auto pt-12 mobilescreen:py-8">
          {canMarkAttendance && (
            <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={actions.handleAttendedClick}
              disabled={
                actions.isUpdating || selectedUsers.length === 0
              }
            >
              {t("COMMON.ATTENDED")}
            </Button>
          )}
        </div>

        {isPaidOpportunity && isOrganization && (
          <ParticipantsPayments
            opportunityId={opportunityId}
            schedule={navState}
            // A refund unlocks that participant's removal above.
            onRefunded={() => void list.refetchRegistrations()}
          />
        )}
      </div>

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

      <DeleteRegistrationModal
        open={actions.showDeleteModal}
        onClose={() => actions.setShowDeleteModal(false)}
        onConfirm={actions.handleDeleteRegistration}
        isDeleting={actions.isDeleting}
        userName={actions.deletingUserName}
        hasHistory={actions.deletingHasHistory}
      />
    </div>
  );
}
