"use client";

import { useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";

import Searchbar from "@/components/ui/Searchbar";
import {
  getAllOpportunities,
  getUserOpportunities,
} from "@/features/opportunities/services/opportunities";
import { toNumber } from "@/lib/helpers";
import { useAuthStore } from "@/store/authStore";
import { FilterModal } from "../ProfileDescriptionTabs";
import { EMPTY_PROFILE_FILTERS, profileOpportunityChip, resolveProfileOpportunityFilters, type FiltersData } from "../profileFilters";
import ProfileVolunteerCard from "../ProfileVolunteerCard";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import ProfileTypeChips, {
  TYPE_CHIPS,
  type TypeChip,
} from "./ProfileTypeChips";
import ProfileRelationSwitch, { type ProfileRelation } from "./ProfileRelationSwitch";

const LIST_FILTER = "profile";

interface ProfileOpportunitiesTabProps {
  /** Set on a public profile; omitted for your own. */
  userId?: string;
  isOwnProfile: boolean;
  /**
   * An individual's list is what they took part in (`/list-user-opportunities/`);
   * a team's is what it organized (`/list-all-opportunities/?filter_type=organized`);
   * an organization's is what it organized or sponsored, by the switch.
   */
  kind?: "individual" | "team" | "organization";
  /** «خبير»: this person runs their own courses, workshops or spaces. */
  isExpert?: boolean;
  /** Shown beside the tag when the payload carries it (own profile only). */
  expertOpportunitiesCount?: number | null;
}

export default function ProfileOpportunitiesTab({
  userId,
  isOwnProfile,
  kind = "individual",
  isExpert = false,
  expertOpportunitiesCount = null,
}: ProfileOpportunitiesTabProps) {
  // Public activity lists participation, excluding provider-created courses
  // without attendance; the server filters registered rows to attended only.
  const listFilter = isOwnProfile ? LIST_FILTER : "registered";
  const isOrganization = kind === "organization";
  // Both list what the account published; only an organization also sponsors.
  const isTeam = kind === "team" || isOrganization;
  const [relation, setRelation] = useState<ProfileRelation>("organized");
  const organizedFilter = isOrganization ? relation : "organized";
  const user = useAuthStore((s) => s.user);
  const [typeChip, setTypeChip] = useState<TypeChip>("all");
  const [searchQuery, setSearchQuery] = useState("");
  const debouncedSearch = useDebouncedValue(searchQuery);
  const [filters, setFilters] = useState<FiltersData>(EMPTY_PROFILE_FILTERS);
  const [filterOpen, setFilterOpen] = useState(false);
  const [clearFiltersKey, setClearFiltersKey] = useState(0);
  const [isFilterDirty, setIsFilterDirty] = useState(false);
  const formikRef = useRef<{ submitForm: () => Promise<void> } | null>(null);

  /*
   * All three chip counts from one request (BE-97 B).
   *
   * The listing now returns `counts: { all, volunteer, development }` beside
   * the envelope. It is computed *after* the `opportunity_type` filter, so
   * this query must not send one — ask unfiltered and read all three. That
   * replaces the three one-row requests this used to make.
   *
   * `limit: 1` still applies: we want the counts, not the rows.
   */
  const { data: countsResponse } = useQuery({
    queryKey: [
      "user-opportunities-counts",
      kind,
      isTeam ? organizedFilter : listFilter,
      userId ?? "me",
      debouncedSearch,
    ],
    queryFn: () => {
      const params = {
        search: debouncedSearch || undefined,
        user_id: isOwnProfile ? undefined : userId,
        page: 1,
        limit: 1,
      };
      return isTeam
        ? getAllOpportunities({ ...params, filter_type: organizedFilter })
        : getUserOpportunities({ ...params, filter_type: listFilter });
    },
    staleTime: 60 * 1000,
  });

  const countOf = (chip: TypeChip): number | null => {
    const counts = countsResponse?.counts as
      Record<string, number | string> | undefined;
    if (counts?.[chip] != null) return toNumber(counts[chip]);
    // Pre-BE-97 server: only the unfiltered total is knowable from here, so
    // the other two chips show no badge rather than a wrong one.
    if (chip !== "all") return null;
    const total = countsResponse?.meta?.pagination?.total;
    return total == null ? null : toNumber(total);
  };

  const typeParam = TYPE_CHIPS.find((chip) => chip.value === typeChip)?.param;
  const listFilters = resolveProfileOpportunityFilters(filters, typeParam);
  const hasAppliedFilters =
    !!filters.startDate ||
    !!filters.endDate ||
    (filters.tags?.length ?? 0) > 0 ||
    !!filters.opportunity_type || !!filters.opportunity_status || !!filters.profile_activity_tag;

  return (
    <div>
      <FilterModal
        open={filterOpen}
        onClose={() => setFilterOpen(false)}
        clearFiltersKey={clearFiltersKey}
        formikRef={formikRef}
        isFilterDirty={isFilterDirty}
        setIsFilterDirty={setIsFilterDirty}
        onApply={(next: FiltersData) => {
          setFilters(resolveProfileOpportunityFilters(next));
          setTypeChip(profileOpportunityChip(next.opportunity_type));
          setFilterOpen(false);
        }}
        onClear={() => {
          setFilters(EMPTY_PROFILE_FILTERS);
          setTypeChip("all");
          setClearFiltersKey((key) => key + 1);
        }}
        filters={{ ...filters, opportunity_type: typeParam || filters.opportunity_type }}
        isEventFilter={false}
        type
        allowDevelopmentRole={kind === "individual"}
      />

      {isOrganization && (
        <ProfileRelationSwitch value={relation} onChange={setRelation} />
      )}
      <div className="profile-opportunities-toolbar mt-4 mb-4 flex flex-wrap items-center justify-between gap-3">
        <ProfileTypeChips
          typeChip={typeChip}
          setTypeChip={chip => {
            setTypeChip(chip);
            setFilters(previous => resolveProfileOpportunityFilters({ ...previous, opportunity_type: TYPE_CHIPS.find(item => item.value === chip)?.param || "", profile_activity_tag: chip === "development" ? previous.profile_activity_tag : "" }));
          }}
          countOf={countOf}
          isExpert={isExpert}
          expertOpportunitiesCount={expertOpportunitiesCount}
        />
        <div className="w-full max-w-full md:w-1/2 md:max-w-[50%] min-w-0 flex-none [&_.searchitms]:!w-full [&_input]:!min-w-0 [&_input]:!w-full">
          <Searchbar
            onFilterClick={() => setFilterOpen(true)}
            onSearchChange={setSearchQuery}
            hasActiveFilters={hasAppliedFilters}
            isLoading={searchQuery !== debouncedSearch}
            onClearFilters={() => {
              setFilters(EMPTY_PROFILE_FILTERS);
              setTypeChip("all");
              setClearFiltersKey((key) => key + 1);
            }}
          />
        </div>
      </div>

      {isTeam ? (
        <ProfileVolunteerCard
          // Keyed so switching lists starts its own scroll and cache.
          key={organizedFilter}
          filter_type={organizedFilter}
          filters={listFilters}
          searchQuery={debouncedSearch}
          currentUser={user}
          isPublicProfile={!isOwnProfile}
          user_id={isOwnProfile ? undefined : userId}
          type={organizedFilter}
          profileBadges={organizedFilter === "sponsored" ? "sponsor" : "organizer"}
        />
      ) : (
        <ProfileVolunteerCard
          filter_type="registered"
          apiFilterType={listFilter}
          filters={listFilters}
          searchQuery={debouncedSearch}
          currentUser={user}
          isPublicProfile={!isOwnProfile}
          user_id={isOwnProfile ? undefined : userId}
          type="registered"
          useNewApi
          profileBadges="individual"
        />
      )}
    </div>
  );
}
