"use client";

import {
  type ChoiceItem,
  type EventCardProps,
  type EventData,
} from "./eventListCardTypes";
import { useState } from "react";
import "react-multi-carousel/lib/styles.css";
import { useRouter } from "next/navigation";
import { useLanguageStore } from "@/store/languageStore";
import { useQuery } from "@tanstack/react-query";
import { getAllEvents } from "@/features/events/services/eventsApi";
import { getDropdownChoices } from "@/features/shared/services/dropdowns";
import moment from "moment";
import "moment/locale/ar";
import { useAuthStore } from "@/store/authStore";
import type { EventTitlePair } from "@/features/events/eventRecord";
import {
  usePageCursor,
  usePagedItems,
} from "@/features/shared/pagedList";
import { useResponsiveValue } from "@/hooks/useViewportWidth";
import { resolveEventTypeId, eventCategoryState } from "./eventTypeLookup";

/** Widest first — see `limit` below. */
const GRID_PAGE_SIZES = [
  { minWidth: 1200, value: 9 },
  { minWidth: 768, value: 8 },
  { minWidth: 0, value: 9 },
] as const;

/**
 * The all-events list's data: the responsive page size, the accumulating pages,
 * and the event-type lookup that has to resolve before the list can query.
 */
export function useEventListCard({
  filters,
  searchQuery = "",
  event_type,
}: EventCardProps) {
  const selectedLanguage = useLanguageStore((s) => s.language);
  const router = useRouter();
    const user = useAuthStore((s) => s.user);
  const [deleteModalInfo, setDeleteModalInfo] = useState<{
    isOpen: boolean;
    eventId?: string;
    eventTitle?: EventTitlePair;
  }>({ isOpen: false });

  /**
   * The page size, chosen so the last row of the grid is never half empty.
   *
   * Two columns take 8 so four rows fill exactly; every other width takes 9.
   * This used to be a `gridColumns` state nobody read, a `limit` state derived
   * from it, and a mount-plus-resize effect that wrote both — one `setState`
   * after paint on every single load. `useResponsiveValue` reads the width
   * through `useSyncExternalStore` instead, so the value is part of the render
   * and the server snapshot is explicit. The `0` row is that server snapshot:
   * before the browser is measured the limit is 9, exactly as the old
   * `useState(calculateOptimalLimit(1))` initial value was.
   */
  const limit = useResponsiveValue(GRID_PAGE_SIZES, 9);

  const { data: eventTypeData, isLoading: eventTypeLoading, isError: eventTypeError, refetch: refetchEventTypes } = useQuery({
    queryKey: ["dropdown", "event_type"],
    queryFn: () => getDropdownChoices("event_type"),
  });

  const eventTypeId = resolveEventTypeId(eventTypeData?.data as ChoiceItem[] | undefined, event_type);

  const categoryState = eventCategoryState(event_type, eventTypeId, eventTypeLoading, eventTypeError);
  const shouldSkipQuery = categoryState !== "all" && categoryState !== "ready";
  const finalEventType = filters?.type || eventTypeId;
  // Clear may replace the filters with a new object containing the same values.
  // Track their query-relevant content so that no-op resets do not erase the
  // locally accumulated list without causing React Query to fetch again.
  const filterSignature = JSON.stringify({
    startDate: filters?.startDate ?? "",
    endDate: filters?.endDate ?? "",
    tags: filters?.tags ?? [],
    eventType: finalEventType ?? "",
    location: filters?.location ?? "",
    gender: filters?.gender ?? "",
    age: filters?.age ?? [null, null],
    participationType: filters?.participation_type ?? "",
    matchMyInterest: filters?.matchMyInterest ?? false,
    status: filters?.status ?? "",
  });

  /* Page and rows both live in `usePagedList`, which performs the reset and the
     append during render. The two effects that used to do it ran after paint,
     so a filter change rendered one frame of the previous filter's events. */
  const { page: currentPage, nextPage, resetPage } = usePageCursor(
    `${filterSignature}|${searchQuery}`
  );

  const {
    data: eventData,
    isLoading: eventLoading,
    isFetching,
    isError: eventError,
    error: eventErrorDetail,
    refetch,
  } = useQuery({
    queryKey: [
      "events-list",
      currentPage,
      limit,
      searchQuery,
      filters?.startDate,
      filters?.endDate,
      filters?.tags,
      finalEventType,
      filters?.location,
      filters?.gender,
      filters?.age,
      filters?.participation_type,
      filters?.matchMyInterest,
      filters?.status,
    ],
    queryFn: () =>
      getAllEvents({
        page: currentPage,
        limit,
        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,
        event_type: finalEventType,
        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,
        participation_type: filters?.participation_type || undefined,
        match_my_interest: filters?.matchMyInterest || undefined,
        status: filters?.status,
      }),
    enabled: !shouldSkipQuery,
  });

  const { items: allEvents, hasMore } = usePagedItems<EventData>({
    resetSignature: `${filterSignature}|${searchQuery}`,
    response: eventData,
    isFetching,
    limit,
  });

  // Keep the settled cards visible while the next search is in flight.
  const [settled, setSettled] = useState({ filterSignature, rows: allEvents, loaded: false });
  if (!isFetching && !eventLoading && !shouldSkipQuery &&
      (settled.rows !== allEvents || settled.filterSignature !== filterSignature || !settled.loaded)) {
    setSettled({ filterSignature, rows: allEvents, loaded: true });
  }
  const hasLoaded = settled.loaded && settled.filterSignature === filterSignature;
  const visibleEvents = isFetching && hasLoaded ? settled.rows : allEvents;

  /* After a delete: `refetch` re-reads only the cursor's page, which
     `usePagedItems` never re-merges past page 1, so a deleted card stayed.
     Back to page 1 (invalidated by `invalidateEventReads`) replaces the list. */
  const reload = () => resetPage();

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

  return {
    eventData,
    eventLoading: eventLoading && !hasLoaded,
    eventError,
    eventErrorDetail,
    refetch,
    reload,
    selectedLanguage,
    router,
    currentPage,
    allEvents: visibleEvents,
    hasMore,
    user,
    deleteModalInfo,
    setDeleteModalInfo,
    limit,
    eventTypeData,
    eventTypeLoading,
    categoryState,
    refetchEventTypes,
    eventTypeId,
    shouldSkipQuery,
    finalEventType,
    filterSignature,
    loadMore,
  };
}
