"use client";

import { useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { normalizeCommunityTag } from "../communityTag";
import { communityDateParams } from "./communityDateFilter";
import { keepPreviousData, useQuery, useQueryClient } from "@tanstack/react-query";
import { getCommunityPosts } from "@/features/community/services/communityApi";
import type { PostData } from "./InnerPost";
import type { CommunityFiltersData } from "./CommunityFilterModal";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import { usePageCursor, usePagedItems } from "@/features/shared/pagedList";
import { communityResetSignature } from "./communityResetSignature";

type PostItem = PostData["data"];

const PAGE_LIMIT = 10;

/**
 * The community feed's data: search, filters and the accumulating page stack.
 *
 * Paging goes through `usePageCursor` / `usePagedItems`, the same primitives
 * the "View All" list (`useCommunityList`) uses and the ones
 * `tests/pagedList.test.ts` covers. This hook used to hand-roll both halves,
 * and both compared by **reference**:
 *
 *  - the reset fired whenever `filters` was a new object, even one holding the
 *    same values;
 *  - the accumulator only folded in a response object it had not already seen.
 *
 * Together those produced an empty feed. Pressing «مسح» with nothing filtered
 * built a fresh — but equal — filters object: the reset cleared the posts, the
 * query key hashed identically so React Query answered from cache with the
 * *same* response object, and the accumulator skipped it as already handled.
 * The list stayed empty until some other filter changed. Typing a search and
 * deleting it again did the same thing.
 *
 * The signature below is built from the filter **values**, so an identical
 * clear is not a change at all; and `usePagedItems` rebuilds from a cache hit
 * when the signature does move, so neither half can leave the list empty.
 */
export function useCommunity() {
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const router = useRouter();
  const tagFromUrl = normalizeCommunityTag(searchParams.get("tag"));
  const clearTag = () => {
    const params = new URLSearchParams(searchParams.toString());
    params.delete("tag");
    router.replace(`${pathname}${params.size ? `?${params}` : ""}`, { scroll: false });
  };
  const [searchQuery, setSearchQuery] = useState("");
  const [openfilter, setOpenfilter] = useState(false);
  const debouncedSearch = useDebouncedValue(searchQuery);

  const [filters, setFilters] = useState<CommunityFiltersData>({
    name: "",
    startDate: "",
    endDate: "",
    type: "",
    tags: [],
  });

  const handleApplyFilters = (
    newFilters: CommunityFiltersData,
    isClear = false
  ) => {
    setFilters(newFilters);
    if (isClear && tagFromUrl) clearTag();
    if (!isClear) setOpenfilter(false);
  };

  /* Compared by value, not by object identity — see the function's own note.
     The same signature the "View All" list builds. */
  const resetSignature = communityResetSignature({
    search: debouncedSearch,
    filters,
    tag: tagFromUrl,
  });
  const { page: currentPage, nextPage, resetPage } = usePageCursor(resetSignature);
  const queryClient = useQueryClient();

  const {
    data: posts,
    isLoading,
    isFetching,
    isError,
    error,
    refetch,
  } = useQuery({
    queryKey: ["communityPosts", currentPage, debouncedSearch, filters, tagFromUrl],
    queryFn: () =>
      getCommunityPosts({
        page: currentPage,
        limit: PAGE_LIMIT,
        search: debouncedSearch,
        ...communityDateParams(filters),
        name: filters?.name,
        /**
         * There is no `type` param on `/posts/` — the endpoint filters on the
         * boolean flags `post` / `proposing_idea` / `is_funding_required`
         * instead, and a `type=` value was accepted and silently ignored
         * (BE-05). The filter modal's own values are already those flag names,
         * so the selection becomes `<flag>=true`. Only `true` is parsed: `=1`
         * falls through to an unfiltered list.
         */
        ...(filters?.type ? { [filters.type]: true } : {}),
        tags: tagFromUrl ? [...new Set([tagFromUrl, ...(filters.tags ?? [])])] : filters.tags?.length ? filters.tags : undefined,
      }),
    // A search or filter change rewrites the query key. Keeping the previous
    // results means `isLoading` stays false, so the posts are not replaced by
    // the full-screen loader on every keystroke — the search field shows a
    // small spinner instead, like /opportunities does.
    placeholderData: keepPreviousData,
  });

  // Only a fresh page-1 fetch (search/filter change) drives the search
  // field's small spinner — paging further down shouldn't.
  const isSearching = isFetching && currentPage === 1;

  /* `dedupeById` because this endpoint can return the same post twice within
     one response, and the page number comes from the response rather than from
     `currentPage`, so a response still in flight for the previous query is not
     merged under the new one. */
  const { items: allPosts, hasMore } = usePagedItems<PostItem>({
    resetSignature,
    response: posts,
    isFetching,
    limit: PAGE_LIMIT,
    dedupeById: true,
  });

  /* After a create, edit or delete: back to a fresh page 1. A plain `refetch`
     only re-reads the page the cursor is on, which past page 1 is never
     re-merged — the deleted card stayed, the edited text stayed old and a new
     post never appeared. */
  const reload = () => {
    resetPage();
    void queryClient.invalidateQueries({ queryKey: ["communityPosts"] });
  };

  const loadMore = () => {
    if (hasMore && !isFetching) {
      nextPage();
    }
  };

  return {
    tagFromUrl,
    clearTag,
    searchQuery,
    setSearchQuery,
    openfilter,
    setOpenfilter,
    filters,
    handleApplyFilters,
    currentPage,
    allPosts,
    hasMore,
    isLoading,
    isSearching,
    refetch,
    reload,
    isError: isError && allPosts.length === 0,
    error,
    loadMore,
  };
}
