"use client";

import Image from "next/image";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { toastApiError } from "@/lib/api/toastApiError";
import InfiniteScroll from "react-infinite-scroll-component";

import { Button } from "@/components/ui/Button";
import { emergencyContactColumns } from "./registrationEmergencyColumns";
import RegisterListRowCells from "./RegisterListRowCells";
import RegistrationsLoadError from "./RegistrationsLoadError";
import { type RegisteredUser } from "./learnServeRegisterListTypes";
import Searchbar from "@/components/ui/Searchbar";
import Table, { TableColumn } from "@/components/ui/Table";
import Loader from "@/components/ui/Loader";
import { SponsorsClient } from "@/features/home";
import { downloadLearnServeRegistrations } from "@/features/opportunities/services/learnServe";
import { NAV_STATE_KEYS } from "@/lib/navigationState";
import { useLanguageStore } from "@/store/languageStore";
import { usePagedRegistrations } from "./usePagedRegistrations";
import { useNavState } from "@/hooks/useNavState";

const asset = (path: string) => `/assets/${path}`;

export interface RegisterListState {
  id?: string;
}

export default function RegisterList() {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);

  // Carried over from the opportunity row that linked here.
  const navState = useNavState<RegisterListState>(NAV_STATE_KEYS.registerList);
  const opportunityId = navState?.id;

  const downloadMutation = useMutation({
    mutationFn: downloadLearnServeRegistrations,
  });

  // Debounce search

  // Reset page and data when search actually changes
  const list = usePagedRegistrations({ opportunityId });

  const columns: TableColumn[] = [
    {
      label: t("COMMON.REGISTERED_LIST"),
      key: "user_full_name",
      type: "custom",
    },
    { label: t("COMMON.EMAIL"), key: "email", type: "email" },
    { label: t("COMMON.CONTACT_NUMBER"), key: "phone_number", type: "contact" },
    // Conditionally add emergency contact columns
    ...emergencyContactColumns(t, list.rows),
  ];

  const handleDownload = async () => {
    if (!opportunityId || downloadMutation.isPending) return;
    try {
      const response = await downloadMutation.mutateAsync({
        opportunity_id: opportunityId,
        search: list.debouncedSearch,
        all_data: true,
      });
      if (response.downloadUrl) {
        const link = document.createElement("a");
        link.href = response.downloadUrl;
        link.download = "List of Registered Participants.xlsx";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
      toast.success(t("COMMON.DOWNLOAD_SUCCESS"));
    } catch (error) {
      toastApiError(error, selectedLanguage, t("COMMON.DOWNLOAD_FAILURE"));
    }
  };

  // `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>
    );
  }

  // Whether to show inline loader (only on very first load)
  const showInitialLoader = list.isLoading && list.rows.length === 0;

  return (
    <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">
        <div className="mobilescreen:w-[100%] flex justify-center pt-10 pb-[70px]">
          <Searchbar
            placeholder={t("COMMON.SEARCH_BY_NAME")}
            showFilterIcon={false}
            onSearchChange={(value) => list.setSearchQuery(value)}
          />
        </div>
        <div className="selectfiled voulnteerlist">
          {showInitialLoader ? (
            <div className="flex justify-center items-center h-64">
              <Loader />
            </div>
          ) : list.loadError ? (
            <RegistrationsLoadError error={list.loadError} language={selectedLanguage} onRetry={() => void list.refetch()} />
          ) : (
            <div
              id="registerlist-scroll-container"
              style={{ maxHeight: "500px", overflowY: "auto" }}
            >
              <InfiniteScroll
                dataLength={list.rows.length}
                next={list.loadMore}
                hasMore={list.hasMore}
                hasChildren={list.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={
                  list.rows.length > 0 ? (
                    <div className="text-center text-gray-500 py-4 text-sm">
                      {t("COMMON.NO_MORE_REGISTERED_USERS")}
                    </div>
                  ) : null
                }
                scrollableTarget="registerlist-scroll-container"
                scrollThreshold={0.8}
              >
                <Table
                  columns={columns}
                  data={list.rows}
                  renderCell={(column, rowData) => (
                    <RegisterListRowCells
                      column={column}
                      rowData={rowData as unknown as RegisteredUser}
                      selectedLanguage={selectedLanguage}
                    />
                  )}
                />
              </InfiniteScroll>
            </div>
          )}
        </div>
        <div className="flex justify-center mx-auto py-12 mobilescreen:py-8">
          <Button
            variant="primary"
            size="medium"
            className="!w-[255px] !h-[48px]"
            onClick={handleDownload}
            disabled={list.rows.length === 0 || downloadMutation.isPending}
          >
            <Image
              src={asset("voluneteerevent/downloadsheet.svg")}
              alt=""
              width={20}
              height={20}
            />{" "}
            {t("COMMON.DOWNLOAD_SHEET")}
          </Button>
        </div>
      </div>
      <div className="border-t border-[#000]/20 pt-12">
        <SponsorsClient />
      </div>
    </div>
  );
}
