"use client";

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

type PostItem = PostData["data"];

const PAGE_LIMIT = 5;

/**
 * The community list's data: search, filters, and the accumulating page stack.
 *
 * Two queries rather than one because `?tag=` is a different endpoint, not a
 * filter on `/posts/`. Exactly one is `enabled` at a time and the results are
 * merged below, so the caller never sees which one ran.
 */
export function useCommunityList() {
  const searchParams = useSearchParams();

  // Extract tag from URL query parameters if it exists
  const tagFromUrl = searchParams.get("tag");
  const isTagView = Boolean(tagFromUrl);

  const [searchQuery, setSearchQuery] = useState("");
  const [openfilter, setOpenfilter] = useState(false);
  /* Was a bespoke `setTimeout` effect that also cleared the list and reset the
     page in the same callback, with a first-render flag to stop it firing on
     mount. The reset is now implied by the signature below, so only the
     debounce itself is left — and that is the one hook in the app. */
  const debouncedSearch = useDebouncedValue(searchQuery);

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

  const handleApplyFilters = (
    newFilters: CommunityFiltersData,
    isClear = false
  ) => {
    setFilters(newFilters); // Update filters state
    if (!isClear) setOpenfilter(false); // Only close if not clear
    /* No explicit list clear: `filters` is part of the reset signature, so the
       page returns to 1 and the accumulated posts are dropped during the render
       that carries the new filters. */
  };

  /* Everything a change of which invalidates the accumulated posts: the tag in
     the URL (which also switches *which* query runs), the settled search text
     and the filter values. Shared with the feed so the two screens cannot
     drift — `JSON.stringify` here was key-order dependent. */
  const resetSignature = communityResetSignature({
    search: debouncedSearch,
    filters,
    tag: tagFromUrl,
  });
  const { page: currentPage, nextPage, resetPage } = usePageCursor(resetSignature);
  const queryClient = useQueryClient();

  // Use the tag-based query if a tag is provided in the URL
  const {
    data: tagPosts,
    isFetching: isTagLoading,
    isError: isTagError,
    error: tagError,
    refetch: refetchTagPosts,
  } = useQuery({
    queryKey: ["communityPostsByTag", tagFromUrl, currentPage],
    queryFn: () =>
      getCommunityPostsByTag({
        tag: tagFromUrl?.toLowerCase() || "",
        page: currentPage,
        limit: PAGE_LIMIT,
      }),
    enabled: isTagView,
  });

  // Use the regular post query if no tag is provided
  const {
    data: regularPosts,
    isFetching: isRegularLoading,
    isError: isRegularError,
    error: regularError,
    refetch: refetchRegularPosts,
  } = useQuery({
    queryKey: [
      "communityPosts",
      currentPage,
      debouncedSearch,
      filters,
    ],
    queryFn: () =>
      getCommunityPosts({
        page: currentPage,
        limit: PAGE_LIMIT,
        search: debouncedSearch,
        ...communityDateParams(filters),
        name: filters?.name,
        // `/posts/` has no `type` param — the filter values are the endpoint's
        // own boolean flags. See the note in `Community.tsx` (BE-05).
        ...(filters?.type ? { [filters.type]: true } : {}),
        tags: filters?.tags?.length ? filters?.tags : undefined,
      }),
    enabled: !isTagView,
  });

  // Combine the data and loading state
  const posts = isTagView ? tagPosts : regularPosts;
  const isLoading = isTagView ? isTagLoading : isRegularLoading;
  const refetch = isTagView ? refetchTagPosts : refetchRegularPosts;
  const isError = isTagView ? isTagError : isRegularError;
  const error = isTagView ? tagError : regularError;

  /*
   * `dedupeById` because this endpoint can return the same post twice — once
   * within a single response, which is why the replaced code deduped page 1
   * against itself, and once across pages when a post is created while the
   * reader is scrolling.
   *
   * The replaced effect had a latent fault the primitive removes: it did not
   * check `isFetching`, so when the page advanced to 2 it re-ran with
   * `currentPage === 2` while `posts` still held page 1, and appended page 1 to
   * itself. Only the id dedupe hid it. `usePagedItems` keys on the page number
   * the *response* reports, so a stale response is simply not merged twice.
   */
  const { items: allPosts, hasMore } = usePagedItems<PostItem>({
    resetSignature,
    response: posts,
    isFetching: isLoading,
    limit: PAGE_LIMIT,
    dedupeById: true,
  });

  /* After a create, edit or delete: a fresh page 1 (see `useCommunity`). */
  const reload = () => {
    resetPage();
    void queryClient.invalidateQueries({ queryKey: [isTagView ? "communityPostsByTag" : "communityPosts"] });
  };

  // Function to load more data
  const loadMore = () => {
    if (hasMore && !isLoading) {
      nextPage();
    }
  };
  return {
    currentPage,
    tagFromUrl,
    isTagView,
    setSearchQuery,
    openfilter,
    setOpenfilter,
    filters,
    handleApplyFilters,
    allPosts,
    hasMore,
    isLoading,
    refetch,
    reload,
    isError: isError && allPosts.length === 0,
    error,
    loadMore,
  };
}
