"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { useInfiniteQuery } from "@tanstack/react-query";
import { MoreProfileFilters } from "./MoreProfileFilterForm";
import {
  getOrganizationProfilesList,
  getVolunteerProfilesList,
  getVolunteerTeamProfilesList,
} from "@/features/profile/services/profileApi";
import {
  type Bucket,
  type UserProfile,
  type ProfilesListParams,
  type ProfilesListResponse,
} from "./MoreProfile";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";

/** The three buckets, in the order the tab strip shows them. */
export const TABS: { bucket: Bucket; labelKey: string }[] = [
  { bucket: "volunteer", labelKey: "COMMON.PROFILES_TAB_INDIVIDUAL" },
  { bucket: "volunteer_team", labelKey: "COMMON.VOLUNTEER.TEAM" },
  { bucket: "organization", labelKey: "COMMON.ORGANIZATION" },
];

/** Each bucket's own dedicated, independently-paginated endpoint. */
const BUCKET_FETCHERS: Record<Bucket, (params: ProfilesListParams) => Promise<ProfilesListResponse>> = {
  volunteer: getVolunteerProfilesList,
  volunteer_team: getVolunteerTeamProfilesList,
  organization: getOrganizationProfilesList,
};

const LIMIT = 15;

function isBucket(value: string | null): value is Bucket {
  return value === "volunteer" || value === "volunteer_team" || value === "organization";
}

/**
 * The profiles directory's data: which bucket is active (from `?tab=`), the
 * search and filters, and the accumulating page stack.
 */
export function useMoreProfile() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const tabParam = searchParams.get("tab");
  const activeBucket: Bucket = isBucket(tabParam) ? tabParam : "volunteer";

  const [searchQuery, setSearchQuery] = useState(
    () => searchParams.get("search") || ""
  );
  const debouncedSearch = useDebouncedValue(searchQuery);
  const [open, setOpen] = useState(false);
  const [clearFiltersKey, setClearFiltersKey] = useState(0);
  const [isFilterDirty, setIsFilterDirty] = useState(false);
  const [isFilterEmpty, setIsFilterEmpty] = useState(true);
  const [filters, setFilters] = useState<MoreProfileFilters>({
    name: searchParams.get("name") || "",
    nickname: searchParams.get("nickname") || "",
    user_type: "",
  });

  const hasAppliedFilters = !!filters.name || !!filters.nickname;

  // Debounce the search box before it feeds the query key.

  // Sync tab + search + filters back to the URL so navigating back restores state.
  useEffect(() => {
    const params = new URLSearchParams();
    params.set("tab", activeBucket);
    if (debouncedSearch) params.set("search", debouncedSearch);
    if (filters.name) params.set("name", filters.name);
    if (filters.nickname) params.set("nickname", filters.nickname);
    router.replace(`${pathname}?${params.toString()}`, { scroll: false });
  }, [activeBucket, debouncedSearch, filters, pathname, router]);

  const {
    data: profileData,
    isLoading: profileLoading,
    isFetching,
    isFetchingNextPage,
    isError,
    error,
    refetch,
    fetchNextPage,
    hasNextPage,
  } = useInfiniteQuery<ProfilesListResponse>({
    queryKey: [
      "profiles-list",
      activeBucket,
      debouncedSearch,
      filters.name,
      filters.nickname,
    ],
    queryFn: ({ pageParam }) =>
      BUCKET_FETCHERS[activeBucket]({
        page: pageParam as number,
        limit: LIMIT,
        search: debouncedSearch,
        name: filters.name,
        // The «اسم المستخدم» field searches the login username (PDF p.12).
        username: filters.nickname,
      }),
    initialPageParam: 1,
    getNextPageParam: (lastPage): number | undefined => {
      const items = lastPage?.data ?? [];
      const pagination = lastPage?.meta?.pagination;
      if (!pagination || items.length === 0) return undefined;
      const nextPage = (pagination.page ?? 1) + 1;
      return nextPage <= (pagination.total_pages ?? 1) ? nextPage : undefined;
    },
    // Bounded: an endless retry kept the grid spinning with no error to act on.
    retry: 2,
    retryDelay: 2000,
    staleTime: 30 * 1000,
  });

  // Flatten every fetched page into one list (deduped by id for safety).
  const allProfiles = useMemo<UserProfile[]>(() => {
    const pages = profileData?.pages ?? [];
    const seen = new Set<number>();
    const result: UserProfile[] = [];
    for (const page of pages) {
      for (const profile of page?.data ?? []) {
        if (profile && !seen.has(profile.id)) {
          seen.add(profile.id);
          result.push(profile);
        }
      }
    }
    return result;
  }, [profileData]);

  // Only the very first load (no data fetched yet for this page) should block
  // the whole page behind the full Loader. Switching tabs/search/filters after
  // that re-queries under a new key but must keep the page chrome in place and
  // show a small spinner in the grid area instead.
  /*
   * Adjusted during render rather than kept in a ref written from an effect.
   * A ref written in an effect and read while rendering makes the render
   * impure: the value depends on whether the effect has run yet, so the same
   * props could render two different trees (and did, under StrictMode's double
   * render). Setting state during render is React's documented way to derive a
   * value from a change in another value — it re-renders immediately, before
   * anything is committed, and never shows the intermediate output.
   */
  const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
  if (!hasLoadedOnce && !profileLoading) setHasLoadedOnce(true);

  const sentinelRef = useRef<HTMLDivElement>(null);
  const nextPageTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [isPendingNextPage, setIsPendingNextPage] = useState(false);

  useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (
          entries[0].isIntersecting &&
          hasNextPage &&
          !isFetching &&
          !isError &&
          !nextPageTimeoutRef.current
        ) {
          setIsPendingNextPage(true);
          nextPageTimeoutRef.current = setTimeout(() => {
            nextPageTimeoutRef.current = null;
            setIsPendingNextPage(false);
            fetchNextPage();
          }, 1000);
        }
      },
      { threshold: 0, rootMargin: "0px 0px 300px 0px" }
    );
    observer.observe(sentinel);
    return () => observer.disconnect();
  }, [allProfiles.length, hasNextPage, isFetching, isError, fetchNextPage]);

  useEffect(() => {
    return () => {
      if (nextPageTimeoutRef.current) {
        clearTimeout(nextPageTimeoutRef.current);
        nextPageTimeoutRef.current = null;
      }
    };
  }, []);

  const handleTabChange = (value: string) => {
    if (!isBucket(value)) return;
    const params = new URLSearchParams(searchParams.toString());
    params.set("tab", value);
    router.replace(`${pathname}?${params.toString()}`, { scroll: false });
  };

  return {
    hasNextPage,
    isError,
    error,
    refetch,
    profileLoading,
    isFetching,
    isFetchingNextPage,
    router,
    pathname,
    searchParams,
    tabParam,
    activeBucket,
    searchQuery,
    setSearchQuery,
    debouncedSearch,
    open,
    setOpen,
    clearFiltersKey,
    setClearFiltersKey,
    isFilterDirty,
    setIsFilterDirty,
    isFilterEmpty,
    setIsFilterEmpty,
    filters,
    setFilters,
    hasAppliedFilters,
    allProfiles,
    hasLoadedOnce,
    setHasLoadedOnce,
    sentinelRef,
    nextPageTimeoutRef,
    isPendingNextPage,
    setIsPendingNextPage,
    handleTabChange,
  };
}
