"use client";

import { useDeferredValue, useRef, useState } from "react";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import moment from "moment";
import { getAllOpportunities, getUserOpportunities } from "@/features/opportunities/services/opportunities";
import { getUserCertificates } from "@/features/profile/services/profileApi";
import { useTranslation } from "react-i18next";
import { ACTIVITY_TAG_TABS } from "./ProfileDescriptionTabs";
import { EMPTY_PROFILE_FILTERS, profileOpportunityChip, resolveProfileOpportunityFilters, type FiltersData } from "./profileFilters";
import { OPPORTUNITY_TYPE_PARAM, isCertificateItem, type CertificateItem, type ListingMode, type OpportunityItem, type OpportunityTypeFilter, type ProfileSection } from "./commonProfileTypes";
import type { PublicProfileResponse } from "./commonProfileTypes";
import { nextProfileListingPage, profileListingRows } from "../profileListingPages";
import { getApiErrorMessages } from "@/lib/api/errors";

/**
 * A public profile's listings: which tab, which filters, and the query behind
 * them.
 *
 * `organized` vs `sponsored` is two different endpoints, not a parameter — one
 * lists what this profile ran, the other what it backed — so the tab choice
 * changes which query runs rather than just its arguments. A volunteer team has
 * no sponsored view, which is why `eventsMode` is pinned for them.
 */
/** What the hook needs about the profile being viewed. */
interface PublicProfileListingsContext {
  userId: string;
  userType: PublicProfileResponse["user_type"];
  /** `is_volunteer_team` — organization-like for opportunities, but teams publish no events, so no Events tab. */
  isVolunteerTeam: boolean;
  isOwnProfile: boolean;
}

export function usePublicProfileListings(
  context: PublicProfileListingsContext
) {
  const { userId, userType, isVolunteerTeam, isOwnProfile } = context;
  const { t, i18n } = useTranslation();

  const [section, setSection] = useState<ProfileSection>("opportunities");
  const [mode, setMode] = useState<ListingMode>("organized");
  // All / Volunteer / Development, applied on top of the organized/sponsored tag
  const [typeFilter, setTypeFilter] = useState<OpportunityTypeFilter>("all");
  // Participant / Provider — the role this profile played in the activity.
  const [activityTag, setActivityTagState] = useState("all");
  const [search, setSearch] = useState("");
  const deferredSearch = useDeferredValue(search);
  /*
   * Pure volunteers never organise events, so they get no Events tab at all.
   * Volunteer teams are organization-like (`is_volunteer_team: true`) and keep
   * the Events tab even if a response ever labels the row
   * `user_type: "volunteer"` — otherwise the team would lose the tab entirely.
   */
  const isVolunteer = userType === "volunteer" && !isVolunteerTeam;

  const [filterOpen, setFilterOpen] = useState(false);
  const [filters, updateFilters] = useState<FiltersData>(EMPTY_PROFILE_FILTERS);
  const setActivityTag = (value: string) => {
    setActivityTagState(value);
    updateFilters(previous => ({ ...previous, profile_activity_tag: value === "all" ? "" : value }));
  };
  const setFilters = (next: FiltersData) => {
    const normalized = resolveProfileOpportunityFilters(next);
    updateFilters(normalized);
    setTypeFilter(profileOpportunityChip(normalized.opportunity_type));
    setActivityTagState(normalized.profile_activity_tag?.toLowerCase() || "all");
  };
  const [clearFiltersKey, setClearFiltersKey] = useState(0);
  const [isFilterDirty, setIsFilterDirty] = useState(false);
  const filterFormRef = useRef<{ submitForm: () => Promise<void> } | null>(null);

  const hasActiveFilters =
    !!filters.startDate ||
    !!filters.endDate ||
    !!filters.category ||
    !!filters.status ||
    (filters.tags?.length ?? 0) > 0 ||
    !!filters.opportunity_type ||
    !!filters.opportunity_status ||
    !!filters.profile_activity_tag;

  const clearFilters = () => {
    setFilters(EMPTY_PROFILE_FILTERS);
    setClearFiltersKey((prev) => prev + 1);
  };

  // The All / Volunteer / Development chips win over the filter modal's type.
  const selectedOpportunityType =
    typeFilter === "all" ? undefined : OPPORTUNITY_TYPE_PARAM[typeFilter];

  // Participant / Provider only applies to development activities.
  const isDevelopmentFilter = isVolunteer && (typeFilter === "development" || filters.opportunity_type === "learn_serve_opportunity");

  // Reset the role when the type moves off Development, so a hidden chip can
  // never keep narrowing the list behind the user's back.
  const handleTypeFilterChange = (value: OpportunityTypeFilter) => {
    setTypeFilter(value);
    updateFilters(previous => resolveProfileOpportunityFilters({ ...previous, opportunity_type: value === "all" ? "" : OPPORTUNITY_TYPE_PARAM[value], profile_activity_tag: value === "development" ? previous.profile_activity_tag : "" }));
    if (value !== "development") setActivityTag("all");
  };

  // Teams have no Sponsor side: the Sponsor button below is hidden for them,
  // so `mode` can only be "sponsored" for a team if the flag resolved after
  // the user already picked it. Derive instead of syncing with an effect —
  // a team always reads as organized without a cascading render.
  const eventsMode: ListingMode = isVolunteerTeam ? "organized" : mode;

  // Same param mapping the owner's own profile uses in ProfileVolunteerCard /
  // ProfileEventCard, so both screens filter identically.
  const filterParams = {
    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?.length ? filters.tags : undefined,
    // Development only, and omitted when the chip is "All" — the API then keeps
    // returning both roles.
    profile_activity_tag: isDevelopmentFilter
      ? filters.profile_activity_tag || ACTIVITY_TAG_TABS.find((tag: { value: string }) => tag.value === activityTag)?.param
      : undefined,
  };

  const listingQuery = useInfiniteQuery({
    queryKey: [
      "public-profile-listing",
      userId,
      userType,
      isVolunteerTeam,
      section,
      mode,
      deferredSearch,
      filters,
      typeFilter,
      activityTag,
    ],
    initialPageParam: 1,
    getNextPageParam: nextProfileListingPage,
    queryFn: ({ pageParam }) => {
      if (isVolunteer && section === "opportunities") {
        // A volunteer profile's single opportunities tab is labeled "Attended"
        // (`COMMON.ATTENDED--` below), not "Organized" — a volunteer account
        // never organizes anything. Match the same `filter_type` the
        // volunteer's own profile sends for this tab (ProfileDescriptionTabs.tsx).
        return getUserOpportunities({
          filter_type: "registered",
          user_id: userId,
          search: deferredSearch || undefined,
          ...filterParams,
          opportunity_type:
            selectedOpportunityType || filters.opportunity_type || undefined,
          opportunity_status: filters.opportunity_status || undefined,
          page: pageParam,
          limit: 30,
        });
      }
      return getAllOpportunities({
        filter_type:
          section === "events"
            ? eventsMode === "organized"
              ? "organized_events"
              : "sponsored_events"
            : mode,
        user_id: userId,
        search: deferredSearch || undefined,
        ...filterParams,
        opportunity_type:
          selectedOpportunityType ||
          filters.opportunity_type ||
          filters.category ||
          undefined,
        status: filters.opportunity_status || filters.status || undefined,
        page: pageParam,
        limit: 30,
      });
    },
    enabled: section !== "certificates",
  });

  const certificatesQuery = useQuery({
    queryKey: ["public-profile-certificates", userId],
    queryFn: () => getUserCertificates(userId),
    // Fetched up front, not just when the tab is open: an empty list hides the
    // tab, the same rule the counters follow. Gated on ownership too, so a
    // visitor never even issues the request for certificates that are not theirs.
    enabled: isVolunteer && isOwnProfile,
  });

  const items: OpportunityItem[] = profileListingRows<OpportunityItem>(listingQuery.data?.pages ?? []);
  // Only well-formed certificate entries reach the grid — if the API ever
  // mixes an opportunity-shaped object into `data`, it is dropped here rather
  // than rendered as a broken tile.
  const certificates: CertificateItem[] = Array.isArray(certificatesQuery.data?.data)
    ? (certificatesQuery.data.data as unknown[]).filter(isCertificateItem)
    : [];
  const loading = section === "certificates" ? certificatesQuery.isLoading : listingQuery.isLoading;
  const activeQuery = section === "certificates" ? certificatesQuery : listingQuery;
  const error = activeQuery.isError ? getApiErrorMessages(activeQuery.error, i18n.language)[0] || t("COMMON.SOMETHING_WENT_WRONG") : null;

  const sections: Array<{ value: ProfileSection; label: string }> = isVolunteer
    ? [
        { value: "opportunities", label: t("COMMON.OPPORTUNITIES-") },
        ...(isOwnProfile && certificates.length > 0
          ? [
              {
                value: "certificates" as ProfileSection,
                label: t("COMMON.CERTIFICATES"),
              },
            ]
          : []),
      ]
    : [
        { value: "opportunities", label: t("COMMON.OPPORTUNITIES-") },
        // Volunteer teams cannot publish events, so a team profile has no
        // Events tab (client answers p.6, additional note).
        ...(isVolunteerTeam ? [] : [{ value: "events" as ProfileSection, label: t("COMMON.EVENTS-") }]),
      ];

  return {
    eventsMode,
    deferredSearch,
    section,
    setSection,
    mode,
    setMode,
    typeFilter,
    handleTypeFilterChange,
    activityTag,
    setActivityTag,
    search,
    setSearch,
    filterOpen,
    setFilterOpen,
    filters,
    setFilters,
    clearFiltersKey,
    isFilterDirty,
    setIsFilterDirty,
    filterFormRef,
    hasActiveFilters,
    clearFilters,
    isDevelopmentFilter,
    items,
    certificates,
    loading,
    sections,
    error,
    retry: () => { void activeQuery.refetch(); },
    hasMore: section !== "certificates" && listingQuery.hasNextPage,
    loadingMore: listingQuery.isFetchingNextPage,
    loadMore: () => { void listingQuery.fetchNextPage(); },
  };
}
