"use client";

import type { EventRecord } from "@/features/events/eventRecord";
import {
  isEventCard,
  type OpportunityCardRecord,
} from "@/features/opportunities/opportunityRecord";
import {
  type ProfileEventCardProps,
} from "./profileEventCardTypes";
import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import moment from "moment";
import { getAllOpportunities } from "@/features/opportunities/services/opportunities";
import { useLanguageStore } from "@/store/languageStore";
import type { EventTitlePair } from "@/features/events/eventRecord";
import {
  usePageCursor,
  usePagedItems,
} from "@/features/shared/pagedList";
import { useResponsiveValue } from "@/hooks/useViewportWidth";

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

/** The confirm-delete dialog's state, shared with the tile that opens it. */
export interface DeleteModalInfo {
  isOpen: boolean;
  eventId?: string;
  eventTitle?: EventTitlePair;
}

/**
 * A profile's events list: the responsive page size, the accumulating pages,
 * and the reset when the search or filters change.
 */
export function useProfileEventCard({
  filter_type,
  filters,
  searchQuery,
  isPublicProfile = false,
  user_id,
}: ProfileEventCardProps) {
  const selectedLanguage = useLanguageStore((s) => s.language);
  const router = useRouter();
  /* Eight per page at two columns so four rows fill exactly; nine everywhere
     else. Read through `useSyncExternalStore` rather than a mount effect — see
     `hooks/useViewportWidth.ts`. */
  const limit = useResponsiveValue(PROFILE_GRID_PAGE_SIZES, 9);

  /* Everything that invalidates the accumulated list. The three refs and the
     "is this the first render" flag this replaces existed only to tell a real
     filter change from the remount React does anyway; comparing the signature
     answers that directly, and does it during render instead of after paint. */
  const resetSignature = JSON.stringify({ filters, searchQuery, filter_type, isPublicProfile, user_id, limit });
  const { page: currentPage, nextPage, resetPage } = usePageCursor(resetSignature);

  const { data, isLoading, isFetching, isError, error, refetch } = useQuery({
    queryKey: [
      "profile-events",
      filter_type,
      searchQuery,
      filters,
      currentPage,
      limit,
      user_id,
    ],
    queryFn: () =>
      getAllOpportunities({
        filter_type,
        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,
        opportunity_type: filters?.category,
        status: filters?.status,
        tags: filters?.tags,
        user_id: isPublicProfile ? user_id : undefined,
        page: currentPage,
        limit,
      }),
  });

  /*
   * Paged over the union the endpoint really returns, then narrowed — not
   * narrowed first. Filtering `data.data` before handing it to
   * `usePagedItems` would build a new envelope object on every render, and the
   * primitive distinguishes a refetch from a re-render by response
   * *identity*; a fresh object each time would make every render look like a
   * new page. Narrowing the merged `items` instead leaves that identity alone.
   *
   * Every `filter_type` this screen passes is event-scoped, so the rows are
   * events in practice — but that is a controller-side guarantee, so the
   * predicate stays rather than an assertion.
   */
  const { items: pagedRows, hasMore } = usePagedItems<
    EventRecord | OpportunityCardRecord
  >({
    resetSignature,
    response: data,
    isFetching,
    limit,
  });

  const events = useMemo(() => pagedRows.filter(isEventCard), [pagedRows]);

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

  const [deleteModalInfo, setDeleteModalInfo] =
    useState<DeleteModalInfo>({ isOpen: false });

  const getStatusStyles = (status: string) => {
    switch (status?.toLowerCase()) {
      case "inprogress":
        return "bg-primary-505 text-primary-5";
      case "completed":
      case "upcoming":
        return "bg-primary-10 text-white";
      default:
        return "";
    }
  };

  const hasNoEvents = !events || events.length === 0;

  return {
    selectedLanguage,
    isError,
    error,
    router,
    events,
    currentPage,
    hasMore,
    limit,
    data,
    isLoading,
    isFetching,
    refetch,
    /* After a delete: a refetch of page n > 1 is never re-merged, so the
       deleted card stayed; page 1 (invalidated by the modal) replaces it. */
    reload: resetPage,
    loadMore,
    deleteModalInfo,
    setDeleteModalInfo,
    getStatusStyles,
    hasNoEvents,
  };
}
