"use client";

import { useEffect, useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { directRegisterVolunteer } from "@/features/opportunities/services/registrations";
import { getAvailableVolunteers } from "@/features/shared/services/directory";
import {
  directRegisterFailures,
  formatDirectRegisterFailures,
  type VolunteerPickerRow,
} from "@/features/opportunities/volunteerPicker";
import { getApiErrorBody, getLocalizedApiMessage } from "@/lib/api/errors";
import {
  usePageCursor,
  usePagedItems,
} from "@/features/shared/pagedList";

/** Five per page — a short list inside a modal, not a full-page feed. */
const AVAILABLE_VOLUNTEERS_LIMIT = 5;

/**
 * The "add volunteers" picker: who can still be registered, five at a time.
 *
 * Two details are deliberate and easy to lose:
 *
 *  - the open/close reset is done by **comparing a prop against state during
 *    render** (React's documented pattern for resetting on a prop change) rather
 *    than in an effect, so the modal never renders one frame of the previous
 *    session's selection;
 *  - `debouncedSearchTerm` is held here rather than through `useDebouncedValue`
 *    because opening has to clear it *immediately* — the query is keyed on it, so
 *    a stale term would fetch the last search's page behind a fresh modal.
 */
export function useAvailableVolunteers({
  open,
  opportunityId,
  selectedLanguage,
  t,
  onClose,
  onRegistered,
}: {
  open: boolean;
  opportunityId?: string;
  selectedLanguage: string;
  t: (key: string, options?: Record<string, unknown>) => string;
  onClose: () => void;
  onRegistered: () => Promise<void> | void;
}) {
  const [searchVolunteerTerm, setSearchVolunteerTerm] = useState("");
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");
  const [selectedVolunteers, setSelectedVolunteers] = useState<number[]>([]);

  const registerVolunteersMutation = useMutation({
    mutationFn: directRegisterVolunteer,
  });

  useEffect(() => {
    const timer = setTimeout(
      () => setDebouncedSearchTerm(searchVolunteerTerm),
      500
    );
    return () => clearTimeout(timer);
  }, [searchVolunteerTerm]);

  /*
   * A fresh start every time the modal opens, and whenever the search changes
   * while it stays open.
   *
   * `openCount` is part of the reset signature rather than `open` itself: two
   * separate openings with the same search term must both clear the list, and a
   * boolean cannot distinguish them. Adjusted during render, which is React's
   * documented pattern for resetting state on a prop change.
   */
  const [wasOpen, setWasOpen] = useState(open);
  const [openCount, setOpenCount] = useState(0);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (open) {
      setSearchVolunteerTerm("");
      setDebouncedSearchTerm("");
      setSelectedVolunteers([]);
      setOpenCount((previous) => previous + 1);
    }
  }

  const resetSignature = `${openCount}|${opportunityId ?? ""}|${debouncedSearchTerm}`;
  const { page: volunteerPage, nextPage } = usePageCursor(resetSignature);

  const availableVolunteersQuery = useQuery({
    queryKey: [
      "available-volunteers",
      opportunityId,
      debouncedSearchTerm,
      volunteerPage,
    ],
    queryFn: () =>
      getAvailableVolunteers({
        opportunity_id: opportunityId || "0",
        type: "volunteer",
        search: debouncedSearchTerm,
        page: volunteerPage,
        limit: AVAILABLE_VOLUNTEERS_LIMIT,
      }),
    enabled: Boolean(opportunityId) && open,
  });

  const availableVolunteers = availableVolunteersQuery.data;
  const fetchingVolunteers = availableVolunteersQuery.isFetching;

  const { items: allVolunteers, hasMore: hasMoreVolunteers } =
    usePagedItems<VolunteerPickerRow>({
      resetSignature,
      response: availableVolunteers,
      isFetching: fetchingVolunteers,
      limit: AVAILABLE_VOLUNTEERS_LIMIT,
    });

  const loadMoreVolunteers = () => {
    if (hasMoreVolunteers && !fetchingVolunteers) {
      nextPage();
    }
  };

  const toggleVolunteerSelection = (volunteerId: number) => {
    setSelectedVolunteers((previous) => {
      const numericId = Number(volunteerId);
      return previous.includes(numericId)
        ? previous.filter((id) => id !== numericId)
        : [...previous, numericId];
    });
  };

  const handleRegisterSelectedVolunteers = async () => {
    if (!opportunityId || selectedVolunteers.length === 0) return;

    try {
      const response = await registerVolunteersMutation.mutateAsync({
        opportunity_id: opportunityId,
        user_ids: selectedVolunteers,
      });
      // 201 means at least one was added, not all of them.
      const refused = directRegisterFailures(response, allVolunteers);
      if (refused.length > 0) {
        toast.warning(
          t("COMMON.VOLUNTEERS_ADDED_PARTIAL", {
            added: response.data?.success_count ?? selectedVolunteers.length - refused.length,
            failed: refused.length,
          }),
          { description: formatDirectRegisterFailures(refused), duration: 12000, classNames: { description: "whitespace-pre-line" } }
        );
      } else {
        toast.success(t("COMMON.VOLUNTEERS_ADDED_SUCCESS"));
      }
      onClose();
      await onRegistered();
    } catch (error) {
      // 400 with every id refused carries the same per-person reasons.
      const refused = directRegisterFailures(getApiErrorBody(error), allVolunteers);
      if (refused.length > 0) {
        toast.error(t("COMMON.VOLUNTEERS_NOT_ADDED"), {
          description: formatDirectRegisterFailures(refused),
          duration: 12000,
          classNames: { description: "whitespace-pre-line" },
        });
        return;
      }
      toast.error(
        getLocalizedApiMessage(
          error,
          selectedLanguage,
          t("COMMON.VOLUNTEERS_ADDED_FAILED")
        )
      );
    }
  };

  return {
    /** The modal's first load only — a search shows `isSearching` instead. */
    isFirstPageLoading:
      availableVolunteersQuery.isLoading &&
      volunteerPage === 1 &&
      debouncedSearchTerm === "",
    /**
     * Typing (the debounce has not fired yet) or the search's first page in
     * flight. Drawn as a spinner in place of the search icon (client,
     * 2026-10-15) rather than a loader over the list.
     */
    isSearching:
      searchVolunteerTerm !== debouncedSearchTerm ||
      (debouncedSearchTerm !== "" && fetchingVolunteers && volunteerPage === 1),
    searchVolunteerTerm,
    setSearchVolunteerTerm,
    selectedVolunteers,
    allVolunteers,
    hasMoreVolunteers,
    fetchingVolunteers,
    isRegistering: registerVolunteersMutation.isPending,
    /** A failed read with nothing listed: not «لا يوجد متطوعين». */
    loadError:
      availableVolunteersQuery.isError && allVolunteers.length === 0
        ? (availableVolunteersQuery.error ?? new Error("load"))
        : null,
    retryVolunteers: () => void availableVolunteersQuery.refetch(),
    loadMoreVolunteers,
    toggleVolunteerSelection,
    handleRegisterSelectedVolunteers,
  };
}
