"use client";

import { useRef, useState } from "react";
import { useResponsiveValue } from "@/hooks/useViewportWidth";
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";
import moment from "moment";
import { useRouter } from "next/navigation";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import apiClient from "@/lib/api/client";
import { getDropdownChoices } from "@/features/shared/services/dropdowns";
import { learningTypeIdForFilterType } from "@/features/opportunities/components/opportunityTypeOptions";
import { useLanguageStore } from "@/store/languageStore";
import {
  getOpportunityAccent,
} from "@/features/opportunities/components/OpportunityCard";
import {
  responsive,
  type VolunteerCardProps,
} from "./volunteerCardTypes";
import { useIsMounted } from "@/hooks/useIsMounted";

/**
 * The home carousel's data: two independent queries (volunteer and
 * learn-&-serve), merged into one list, plus the slide bookkeeping.
 */
export function useVolunteerCard({
  isOpportunity,
  isLearnServe,
  is_homepage,
  filters,
  searchQuery,
  initialData,
}: VolunteerCardProps) {
  const selectedLanguage = useLanguageStore((s) => s.language);
  const [currentSlide, setCurrentSlide] = useState(0);
  /*
   * `maxVisibleItems` is a measurement of the viewport, not state this
   * component owns. It was `useState` seeded with a guess and overwritten by a
   * mount effect plus a `resize` listener — the shape
   * `react-hooks/set-state-in-effect` flags, and the one `useViewportWidth`
   * exists for. `useResponsiveValue` reads the same three breakpoints through
   * `useSyncExternalStore`, which has a separate server snapshot and so needs
   * no post-mount write.
   *
   * Before measurement the value is the narrowest entry rather than the old
   * hard-coded 3. Only the arrow/dot visibility reads it — the carousel
   * itself takes `responsive` directly — so this affects one frame on first
   * paint, mobile-first, which is the direction the effect corrected to
   * anyway.
   */
  const maxVisibleItems = useResponsiveValue(
    [
      { minWidth: 1200, value: responsive.superLargeDesktop.items },
      { minWidth: 991, value: responsive.desktop.items },
      { minWidth: 768, value: responsive.smallDesktop.items },
      { minWidth: 0, value: responsive.tablet.items },
    ],
    responsive.tablet.items
  );
  const carouselRef = useRef<Carousel>(null);
  const router = useRouter();
  const accent = getOpportunityAccent({
    isLearnServe,
    isOpportunity,
    isHomepage: is_homepage,
  });

  const isMounted = useIsMounted();

  const queryParamsForOpportunity = {
    page: 1,
    limit: 6,
    search: searchQuery,
    start_date: filters?.startDate ? moment(filters.startDate).format("YYYY-MM-DD") : undefined,
    end_date: filters?.endDate ? moment(filters.endDate).format("YYYY-MM-DD") : undefined,
    tags: filters?.tags,
    location: filters?.location,
    gender: filters?.gender,
    min_age: typeof filters?.age?.[0] === "number" ? filters.age[0] : undefined,
    max_age: typeof filters?.age?.[1] === "number" ? filters.age[1] : undefined,
    opportunity_nationality: filters?.opportunity_nationality,
    type: filters?.type,
    is_relief: filters?.isRelief || undefined,
    // «طوارئ» is `is_emergency`, as on the volunteer list (opportunityListQueryParams).
    is_emergency: filters?.isUrgent || undefined,
    is_supports_disabled: filters?.isSpecialNeed || undefined,
    match_my_interest: filters?.matchMyInterest || undefined,
    status: filters?.status,
    sort_by: filters?.sortBy || undefined,
  };

  /* A mixed list's «النوع» is a `filter-type` id; the development endpoint only
     filters by `learning_type_id`, so translate it (same cached dropdowns as
     the filter modal). */
  const { data: filterTypeChoices } = useQuery({
    queryKey: ["dropdown", "filter-type"],
    queryFn: () => getDropdownChoices("filter-type"),
    enabled: Boolean(filters?.type),
  });
  const { data: learningTypeChoices } = useQuery({
    queryKey: ["dropdown", "learning_type"],
    queryFn: () => getDropdownChoices("learning_type"),
    enabled: Boolean(filters?.type),
  });
  const learningTypeId = learningTypeIdForFilterType(
    filters?.type,
    filterTypeChoices?.data,
    learningTypeChoices?.data
  );

  const queryParamsForLearnServe = {
    page: 1,
    limit: 6,
    search: searchQuery,
    start_date: filters?.startDate ? moment(filters.startDate).format("YYYY-MM-DD") : undefined,
    end_date: filters?.endDate ? moment(filters.endDate).format("YYYY-MM-DD") : undefined,
    tags: filters?.tags,
    location: filters?.location,
    gender: filters?.gender,
    min_age: typeof filters?.age?.[0] === "number" ? filters.age[0] : undefined,
    max_age: typeof filters?.age?.[1] === "number" ? filters.age[1] : undefined,
    opportunity_nationality: filters?.opportunity_nationality,
    // `type` still empties the list for «Volunteer»; the rest need the id.
    type: filters?.type,
    learning_type_id: learningTypeId,
    in_person: filters?.isInPerson || undefined,
    online: filters?.isOnline || undefined,
    match_my_interest: filters?.matchMyInterest || undefined,
    status: filters?.status,
    sort_by: filters?.sortBy || undefined,
  };

  const { data: volunteerResponse, isLoading: volunteerLoading, isError: volunteerError, error: volunteerErrorValue, refetch: refetchVolunteer } = useQuery({
    queryKey: ["volunteer-opportunities", queryParamsForOpportunity],
    queryFn: async () => {
      const { data } = await apiClient.get("/list-volunteer-opportunities/", {
        params: queryParamsForOpportunity,
      });
      return data;
    },
    enabled: !!isOpportunity && !isLearnServe,
    // Seed with server data so no client fetch is needed on first paint. An
    // EMPTY server list is not seeded — `initialData` counts as fresh for
    // `staleTime`, so it would pin the section empty instead of retrying.
    initialData: is_homepage && initialData?.length && !isLearnServe
      ? { data: initialData }
      : undefined,
    staleTime: is_homepage ? 2 * 60 * 1000 : 0,
    // A search or filter change rewrites the query key. Keeping the previous
    // page's results means `isLoading` stays false, so the section is not
    // replaced by the full-screen loader on every keystroke.
    placeholderData: keepPreviousData,
  });

  const { data: learnServeResponse, isLoading: learnServeLoading, isError: learnServeError, error: learnServeErrorValue, refetch: refetchLearnServe } = useQuery({
    queryKey: ["learn-serve-opportunities", queryParamsForLearnServe],
    queryFn: async () => {
      const { data } = await apiClient.get("/learn-serve-opportunities/", {
        params: queryParamsForLearnServe,
      });
      return data;
    },
    enabled: !!isLearnServe,
    // Same as above — only a non-empty server list is treated as seeded data.
    initialData: is_homepage && initialData?.length && isLearnServe
      ? { data: initialData }
      : undefined,
    staleTime: is_homepage ? 2 * 60 * 1000 : 0,
    placeholderData: keepPreviousData,
  });

  const data = isLearnServe ? learnServeResponse?.data : volunteerResponse?.data;
  const isLoading = isLearnServe ? learnServeLoading : volunteerLoading;
  /* A failed request is an error with a retry, not «لا توجد فرص». */
  const isError = isLearnServe ? learnServeError : volunteerError;
  const error = isLearnServe ? learnServeErrorValue : volunteerErrorValue;
  const retry = () => { void (isLearnServe ? refetchLearnServe() : refetchVolunteer()); };

  /*
   * Derived, not stored. `totalItems` was `useState(0)` written by a mount /
   * data effect, so on the first render after new data it was still the
   * previous length — which is what `goToNext` and the arrow-disabled checks
   * read, briefly disabling "next" on a list that had just grown. It is
   * `data?.length ?? 0` and nothing else, so it is computed here.
   */
  const totalItems = data?.length ?? 0;

  const goToPrevious = () => {
    if (carouselRef.current && currentSlide > 0) {
      carouselRef.current.previous(1);
      setCurrentSlide((prev) => Math.max(prev - 1, 0));
    }
  };

  const goToNext = () => {
    const maxSlideIndex = Math.max(0, totalItems - maxVisibleItems);
    if (carouselRef.current && currentSlide < maxSlideIndex) {
      carouselRef.current.next(1);
      setCurrentSlide((prev) => Math.min(prev + 1, maxSlideIndex));
    }
  };

  // Inline: this is one section of a page, not the page itself. Re-searches
  // never reach here — `keepPreviousData` holds the previous list on screen and
  // the search bar shows the in-flight spinner instead.
  return {
    selectedLanguage,
    currentSlide,
    setCurrentSlide,
    totalItems,
    maxVisibleItems,
    carouselRef,
    router,
    accent,
    isMounted,
    queryParamsForOpportunity,
    queryParamsForLearnServe,
    volunteerResponse,
    volunteerLoading,
    learnServeResponse,
    learnServeLoading,
    data,
    isLoading,
    isError,
    error,
    retry,
    goToPrevious,
    goToNext,
  };
}
