"use client";

import { useTranslation } from "react-i18next";
import InfiniteScroll from "react-infinite-scroll-component";
import Loader from "@/components/ui/Loader";
import { getDefaultProfileImage } from "@/lib/helpers";
import { maskedIdentifier } from "./maskedIdentifier";
import type { VolunteerPickerRow } from "@/features/opportunities/volunteerPicker";
import RemoteImage from "@/components/ui/RemoteImage";
import ProfileLink from "@/components/shared/ProfileLink";
import { useLanguageStore } from "@/store/languageStore";
import RegistrationsLoadError from "./RegistrationsLoadError";

interface AvailableVolunteersListProps {
  isFirstPageLoading: boolean;
  /** A search is running: hold the space quietly instead of "none found". */
  isSearching?: boolean;
  allVolunteers: VolunteerPickerRow[];
  hasMoreVolunteers: boolean;
  loadMoreVolunteers: () => void;
  selectedVolunteers: number[];
  toggleVolunteerSelection: (volunteerId: number) => void;
  loadError?: unknown;
  onRetry?: () => void;
}

/**
 * The scrolling list of volunteers who may still be added.
 *
 * Scrolls inside its own 24rem box, so `scrollableTarget` has to name that
 * element or the next page never loads on a tall screen.
 */
export default function AvailableVolunteersList({
  isFirstPageLoading,
  isSearching = false,
  allVolunteers,
  hasMoreVolunteers,
  loadMoreVolunteers,
  selectedVolunteers,
  toggleVolunteerSelection,
  loadError,
  onRetry,
}: AvailableVolunteersListProps) {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);

  return (
    <>
        {isFirstPageLoading ? (
          <div className="flex justify-center py-8">
            <Loader inline size="sm" />
          </div>
        ) : loadError ? (
          <RegistrationsLoadError error={loadError} language={language} onRetry={onRetry} />
        ) : allVolunteers.length === 0 && isSearching ? (
          <div className="min-h-[120px]" aria-hidden />
        ) : allVolunteers.length === 0 ? (
          <div className="max-h-96 overflow-y-auto">
            <div className="text-center text-gray-500 p-4">
              {t("COMMON.NO_VOLUNTEERS_FOUND")}
            </div>
          </div>
        ) : (
          <div
            id="volunteers-scroll-container"
            className="max-h-96 overflow-y-auto"
          >
            <InfiniteScroll
              dataLength={allVolunteers.length}
              next={loadMoreVolunteers}
              hasMore={hasMoreVolunteers}
              hasChildren={allVolunteers.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={
                <div className="text-center text-gray-500 py-4 text-sm">
                  {t("COMMON.NO_MORE_VOLUNTEERS")}
                </div>
              }
              scrollableTarget="volunteers-scroll-container"
            >
              <div className="space-y-2">
                {allVolunteers.map((volunteer) => {
                  const volunteerId = Number(
                    volunteer.user_id || volunteer.user?.id || volunteer.id
                  );
                  const isSelected = selectedVolunteers.includes(volunteerId);
                  /*
                   * `VolunteerPickerResource` sends `full_name` at the top
                   * level *and* on the nested `user`, both from the same
                   * `fullName()` call, so either works; the nested one is
                   * tried first because that is where it was found when the
                   * list was showing no names at all.
                   */
                  const name =
                    volunteer.user?.full_name ||
                    volunteer.full_name ||
                    volunteer.nickname ||
                    "";
                  /*
                   * Whichever identifier the organizer might have searched by.
                   *
                   * BE-82 replaced the full values with `*_last4` — enough to
                   * confirm the right person was found, never enough to use.
                   * The full-value fallbacks that used to be passed here
                   * (`civil_id`, `passport_number`, `phone_number`, and the
                   * same three off the nested `user`) are gone: none of them
                   * is a key `VolunteerPickerResource` emits, so they were
                   * reading `undefined` on every row.
                   */
                  const identifiers = [
                    maskedIdentifier(volunteer.civil_id_last4),
                    maskedIdentifier(volunteer.passport_last4),
                    maskedIdentifier(volunteer.phone_last4),
                  ].filter(Boolean);

                  return (
                    <div
                      key={volunteerId}
                      className={`border rounded-md p-3 flex items-center gap-3 ${
                        isSelected ? "bg-primary-5/10 border-primary-5" : ""
                      }`}
                    >
                      <div className="flex-shrink-0">
                        <RemoteImage
  src={
                            volunteer.user?.profile_pic ||
                            getDefaultProfileImage(
                              /* Top level, not under `user`: the nested object
                                 is only id/full_name/profile_pic/nickname, so
                                 reading it there silently fell through to the
                                 neutral silhouette for every volunteer. */
                              volunteer.gender_display?.value_en,
                              "/assets/profile/male_profile.svg",
                              "/assets/profile/female_profile.svg",
                              "/assets/profile/org_profile.svg"
                            )
                          }
  alt={name}
  width={48}
  height={48}
  className={"w-12 h-12 rounded-full object-cover"}
/>
                      </div>
                      <div className="flex-grow">
                        <div className="font-medium">
                          <ProfileLink
                            id={volunteer.user_id || volunteer.id}
                            className="cursor-pointer text-primary-5"
                          >
                            {name}
                          </ProfileLink>
                        </div>
                        {identifiers.length > 0 && (
                          <div className="text-xs text-gray-500" dir="ltr">
                            {identifiers.join(" · ")}
                          </div>
                        )}
                        {/*
                          The email line that used to sit here is removed:
                          BE-82's picker payload has no `email`, so it rendered
                          an empty row under every name.
                        */}
                      </div>
                      <div className="flex-shrink-0 p-2">
                        <input
                          type="checkbox"
                          checked={isSelected}
                          onChange={() => toggleVolunteerSelection(volunteerId)}
                          aria-label={t("COMMON.SELECT_PERSON_NAMED", { name: volunteer?.user?.full_name ?? "" })}
                          className="h-5 w-5 text-primary-5 rounded focus:ring-primary-5 cursor-pointer"
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            </InfiniteScroll>
          </div>
        )}
    </>
  );
}
