"use client";

import { useTranslation } from "react-i18next";
import InfiniteScroll from "react-infinite-scroll-component";
import Table, { type TableColumn } from "@/components/ui/Table";
import Loader from "@/components/ui/Loader";
import RegistrationRowCells from "./RegistrationRowCells";
import { type RegisteredUser } from "./learnServeRegisterListTypes";
import RegistrationsLoadError from "./RegistrationsLoadError";

interface RegisterListTableProps {
  showInitialLoader: boolean;
  columns: TableColumn[];
  rows: RegisteredUser[];
  hasMore: boolean;
  loadMore: () => void;
  selectedLanguage: string;
  selectedUsers: string[];
  onToggle: (userId: string | number) => void;
  isAfterAttendanceDeadline: boolean;
  canMarkAttendance?: boolean;
  opportunityId?: string;
  onAttendanceUndone?: () => void;
  /** See `RegistrationRowCells`. */
  deleteBlockedLabelFor?: (row: RegisteredUser) => string | null;
  onDelete: (userId: string | number, userName: string) => void;
  windowWidth: number;
  /** A failed first read: shown as an error with a retry, not as "no data". */
  loadError?: unknown;
  onRetry?: () => void;
}

/**
 * The scrolling registrations table.
 *
 * The scroll container is the `div` rather than the window: the table is capped
 * at 500px and paged from its own scrollbar, so `scrollableTarget` has to name
 * that element or the next page never loads on a tall screen.
 */
export default function RegisterListTable({
  showInitialLoader,
  columns,
  rows,
  hasMore,
  loadMore,
  selectedLanguage,
  selectedUsers,
  onToggle,
  isAfterAttendanceDeadline,
  canMarkAttendance = false,
  opportunityId, onAttendanceUndone,
  deleteBlockedLabelFor,
  onDelete,
  windowWidth,
  loadError,
  onRetry,
}: RegisterListTableProps) {
  const { t } = useTranslation();

  if (showInitialLoader) {
    return (
      <div className="flex justify-center items-center h-64">
        <Loader />
      </div>
    );
  }

  if (loadError) {
    return <RegistrationsLoadError error={loadError} language={selectedLanguage} onRetry={onRetry} />;
  }

  return (
    <div
      id="ls-registrations-scroll-container"
      style={{ maxHeight: "500px", overflowY: "auto" }}
    >
      <InfiniteScroll
        dataLength={rows.length}
        next={loadMore}
        hasMore={hasMore}
        hasChildren={rows.length > 0}
        loader={
          <div className="text-center py-4">
            <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary-5" />
          </div>
        }
        endMessage={
          rows.length > 0 ? (
            <div className="text-center text-gray-500 py-4 text-sm">
              {t("COMMON.NO_MORE_REGISTERED_USERS")}
            </div>
          ) : null
        }
        scrollableTarget="ls-registrations-scroll-container"
        scrollThreshold={0.8}
      >
        <Table
          columns={columns}
          data={rows}
          // `Table` types its rows as `Record<string, any>`; this screen knows
          // what they actually are, so the narrowing happens here rather than
          // every cell taking an untyped row.
          renderCell={(column, rowData) => (
            <RegistrationRowCells
              column={column}
              rowData={rowData as unknown as RegisteredUser}
              selectedLanguage={selectedLanguage}
              selectedUsers={selectedUsers}
              onToggle={onToggle}
              isAfterAttendanceDeadline={isAfterAttendanceDeadline}
              canMarkAttendance={canMarkAttendance}
              opportunityId={opportunityId} onAttendanceUndone={onAttendanceUndone}
              deleteBlockedLabelFor={deleteBlockedLabelFor}
              onDelete={onDelete}
              windowWidth={windowWidth}
            />
          )}
        />
      </InfiniteScroll>
    </div>
  );
}
