"use client";

import type { EventRecord } from "@/features/events/eventRecord";
import { isOpportunityCard } from "@/features/opportunities/opportunityRecord";
import type { DeleteOpportunityInfo } from "./ProfileDeleteOpportunityModal";
import {
  type OpportunityData,
  type ProfileVolunteerCardProps,
} from "./profileVolunteerCardTypes";
import { useMemo, useState } from "react";
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;
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import moment from "moment";
import { getAllOpportunities, getUserOpportunities } from "@/features/opportunities/services/opportunities";

const asset = (path: string) => `/assets/${path}`;

/**
 * A profile's opportunities list.
 *
 * Which endpoint it calls depends on the tab: `useNewApi` switches the
 * registered/attended tabs onto the newer per-user endpoint, while organised
 * and sponsored stay on the original one.
 */
export function useProfileVolunteerCard({
  filter_type,
  filters,
  searchQuery = "",
  isPublicProfile = false,
  user_id,
  type,
  useNewApi = false,
  apiFilterType,
}: Omit<ProfileVolunteerCardProps, "profileBadges">) {
  const router = useRouter();

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

  // Infinite scroll state

  // Calculate optimal limit based on grid columns
  /* Eight per page at two columns so four rows fill exactly, nine otherwise.
     Read through `useSyncExternalStore` instead of a mount effect — see
     `hooks/useViewportWidth.ts`. */
  const limit = useResponsiveValue(PROFILE_GRID_PAGE_SIZES, 9);

  /* The three refs and the first-render flag this replaces existed only to tell
     a real filter change from an ordinary re-render. Comparing the signature
     answers that directly, during render rather than after paint. */
  const resetSignature = JSON.stringify({ filters, searchQuery, filter_type, apiFilterType, useNewApi, isPublicProfile, user_id, limit });
  const { page: currentPage, nextPage } = usePageCursor(resetSignature);

  // Use new API only when explicitly told to (volunteer profile's registered/organized tabs)
  const isNewApiTab =
    useNewApi && (filter_type === "registered" || filter_type === "organized");

  /**
   * On `/list-user-opportunities/` the tab this component calls "organized" has
   * never filtered by creator — it has always meant "completed, with at least
   * one attended registration", which is why the UI labels it Attended. The
   * backend gave that query its real name in BE-14; `organized` still runs the
   * identical query for back-compat, but `attended` is the going-forward value.
   * The prop keeps the old name because it also drives this card's styling and
   * the legacy `/list-all-opportunities/` path, where `organized` genuinely
   * does mean created-by-me.
   */
  const userOpportunitiesFilterType =
    apiFilterType ?? (filter_type === "organized" ? "attended" : filter_type);

  const commonParams = {
    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,
    // Participant / Provider. Omitted when the chip is "All", so the API keeps
    // returning both roles.
    profile_activity_tag: filters?.profile_activity_tag || undefined,
    user_id: isPublicProfile ? user_id : undefined,
    page: currentPage,
    limit,
  };

  const newQuery = useQuery({
    queryKey: [
      "user-opportunities",
      userOpportunitiesFilterType,
      commonParams,
      filters,
    ],
    queryFn: () =>
      getUserOpportunities({
        ...commonParams,
        filter_type: userOpportunitiesFilterType,
        opportunity_type: filters?.opportunity_type,
        opportunity_status: filters?.opportunity_status,
      }),
    enabled: isNewApiTab,
  });

  const oldQuery = useQuery({
    queryKey: ["all-opportunities", filter_type, commonParams, filters],
    queryFn: () =>
      getAllOpportunities({
        ...commonParams,
        filter_type: filter_type === "registered" ? "volunteer" : filter_type,
        opportunity_type: filters?.opportunity_type || filters?.category,
        status: filters?.opportunity_status || filters?.status,
      }),
    enabled: !isNewApiTab,
  });

  // Use the appropriate data based on the tab
  const { data, isLoading, isFetching, isError, error, refetch } = isNewApiTab
    ? newQuery
    : oldQuery;

  /*
   * `/list-all-opportunities/` is a **mixed** list — volunteer cards, learn &
   * serve cards and *event* cards — so it is paged as the union and narrowed
   * afterwards. Narrowing `data.data` first would mean a new envelope object
   * each render, and `usePagedItems` tells a refetch from a re-render by
   * response identity; that would make every render look like a fresh page.
   */
  const { items: pagedRows, hasMore } = usePagedItems<
    OpportunityData | EventRecord
  >({
    resetSignature,
    response: data,
    isFetching,
    limit,
  });

  const opportunities = useMemo(
    () => pagedRows.filter(isOpportunityCard),
    [pagedRows]
  );

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

  const isVolunteerOpportunity = (opportunity_type: string) =>
    opportunity_type === "volunteer_opportunity";

  const getStatusStyles = (status: string, opportunity_type: string) => {
    switch (status?.toLowerCase()) {
      case "inprogress":
        return "bg-primary-505 text-primary-5";
      case "completed":
        if (!type) return "";
        if (type === "attendee") return "bg-primary-803 text-white";
        return isVolunteerOpportunity(opportunity_type)
          ? "bg-primary-802 text-white"
          : "bg-primary-803 text-white";
      case "upcoming":
        return "bg-primary-10 text-white";
      default:
        return "";
    }
  };

  const getBgClassByType = (opportunity_type: string) => {
    if (!type) return "bg-primary-802";
    if (type === "attendee") return "bg-primary-803";
    return isVolunteerOpportunity(opportunity_type)
      ? "bg-primary-802"
      : "bg-primary-803";
  };

  const getBorderClassByType = (opportunity_type: string) => {
    if (!type) return "border-primary-802";
    if (type === "attendee") return "border-primary-803";
    return isVolunteerOpportunity(opportunity_type)
      ? "border-primary-802"
      : "border-primary-803";
  };

  const getDeleteIconByType = (opportunity_type: string) => {
    if (type === "attendee")
      return asset("voluneteerevent/card_delete_icon_organized.svg");
    return isVolunteerOpportunity(opportunity_type)
      ? asset("voluneteerevent/card_delete_icon_blue.svg")
      : asset("voluneteerevent/card_delete_icon_organized.svg");
  };

  const getPersonIconByType = (opportunity_type: string) => {
    if (type === "attendee") return asset("homepage/person_icon_organized.svg");
    return isVolunteerOpportunity(opportunity_type)
      ? asset("homepage/person_icon_blue.svg")
      : asset("homepage/person_icon_organized.svg");
  };

  // `isOnlineFormat` lived here too — OpportunityCard owns that decision now,
  // along with the online/location icon it drives.

  const detailHref = (item: OpportunityData) =>
    isVolunteerOpportunity(item.opportunity_type)
      ? `/volunteer-event-detail/${item.id}`
      : `/learn-share-event-detail/${item.id}`;

  const hasNoOpportunities = !opportunities || opportunities.length === 0;

  return {
    router,
    opportunities,
    deleteModalInfo,
    setDeleteModalInfo,
    currentPage,
    hasMore,
    limit,
    isNewApiTab,
    userOpportunitiesFilterType,
    commonParams,
    newQuery,
    oldQuery,
    data,
    isLoading,
    isFetching,
    isError,
    error,
    refetch,
    loadMore,
    isVolunteerOpportunity,
    getStatusStyles,
    getBgClassByType,
    getBorderClassByType,
    getDeleteIconByType,
    getPersonIconByType,
    detailHref,
    hasNoOpportunities,
  };
}
