"use client";

import { useTranslation } from "react-i18next";
import { useRef } from "react";
import { X } from "lucide-react";

import { Button } from "@/components/ui/Button";
import { Modal } from "@/components/ui/Modal";
import { useLanguageStore } from "@/store/languageStore";
import { useAvailableVolunteers } from "./useAvailableVolunteers";
import AvailableVolunteersList from "./AvailableVolunteersList";
import AssetIcon from "@/components/ui/AssetIcon";

interface AddVolunteersModalProps {
  open: boolean;
  onClose: () => void;
  opportunityId: string | undefined;
  /** Called after volunteers are successfully registered, so the caller can refresh its list. */
  onRegistered: () => void | Promise<void>;
}

/**
 * One identifier line under a volunteer's name.
 *
 * The picker endpoints send `*_last4` (BE-82) — the last four characters, so
 * the organizer can tell two people apart without the payload carrying a
 * usable civil ID or passport. Rendered with a leading ellipsis so a partial
 * value never reads as a whole one. `full` is the pre-BE-82 field, kept so the
 * list still says something useful against an older server.
 */
export default function AddVolunteersModal({
  open,
  onClose,
  opportunityId,
  onRegistered,
}: AddVolunteersModalProps) {
  const { t } = useTranslation();
  const searchRef = useRef<HTMLInputElement>(null);
  const selectedLanguage = useLanguageStore((s) => s.language);

  const picker = useAvailableVolunteers({
    open,
    opportunityId,
    selectedLanguage,
    t,
    onClose,
    onRegistered,
  });

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={t("COMMON.AVAILABLE_VOLUNTEERS")}
      size="md"
      footer={
        <div className="flex xss:flex-col justify-center w-full gap-5">
          <Button
            variant="primary"
            size="medium"
            className="xss:!w-full"
            disabled={
              picker.selectedVolunteers.length === 0 || picker.isRegistering
            }
            onClick={picker.handleRegisterSelectedVolunteers}
          >
            {t("COMMON.ADD")}
          </Button>
          <Button
            variant="secondary"
            size="medium"
            className="xss:!w-full"
            onClick={onClose}
            disabled={picker.isRegistering}
          >
            {t("COMMON.CANCEL")}
          </Button>
        </div>
      }
    >
      <div className="pb-10">
        <div className="mb-4 flex items-center searchitms bg-white border border-primary-5/20 rounded-full px-4 py-2">
          {/* 30x30 intrinsic; the classes keep the rendered size. A small
              spinner takes the icon's place while a search is running. */}
          {picker.isSearching ? (
            <span
              className="mx-1 block h-5 w-5 shrink-0 animate-spin rounded-full border-[2.5px] border-primary-5/30 border-t-primary-5"
              role="status"
              aria-label={t("COMMON.LOADING")}
            />
          ) : (
            <AssetIcon
              src="/assets/profile/searchicn.svg"
              size={30}
              className="lg:w-auto md:w-5"
            />
          )}
          <input
            ref={searchRef}
            type="text"
            value={picker.searchVolunteerTerm}
            placeholder={t("COMMON.SEARCH_VOLUNTEERS_BY_IDENTITY")}
            className="flex-1 outline-none bg-transparent px-2 2xl:text-[25px] lg:text-lg xss:text-base laptopmain:text-xl lg:w-auto md:w-[150px] w-[150px] placeholder:text-[#181822CC]/80"
            onChange={(event) =>
              picker.setSearchVolunteerTerm(event.target.value)
            }
          />
          {picker.searchVolunteerTerm && (
            <button
              type="button"
              aria-label={t("COMMON.CLEAR_VOLUNTEER_SEARCH")}
              title={t("COMMON.CLEAR_VOLUNTEER_SEARCH")}
              className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-primary-5 hover:bg-primary-5/10"
              onClick={() => {
                picker.setSearchVolunteerTerm("");
                searchRef.current?.focus();
              }}
            >
              <X size={17} />
            </button>
          )}
        </div>

        {picker.selectedVolunteers.length > 0 && (
          <div className="mb-4 text-primary-5 font-medium">
            {t("COMMON.SELECTED_VOLUNTEERS")}:{" "}
            {picker.selectedVolunteers.length}
          </div>
        )}

        <AvailableVolunteersList
          isFirstPageLoading={picker.isFirstPageLoading}
          isSearching={picker.isSearching}
          allVolunteers={picker.allVolunteers}
          hasMoreVolunteers={picker.hasMoreVolunteers}
          loadMoreVolunteers={picker.loadMoreVolunteers}
          selectedVolunteers={picker.selectedVolunteers}
          toggleVolunteerSelection={picker.toggleVolunteerSelection}
          loadError={picker.loadError}
          onRetry={picker.retryVolunteers}
        />
      </div>
    </Modal>
  );
}
