"use client";

import { useRef, useState } from "react";
import Searchbar from "@/components/ui/Searchbar";
import { useAuthStore } from "@/store/authStore";
import ProfileVolunteerCard from "./ProfileVolunteerCard";
import ProfileTabsBar from "./ProfileTabsBar";
import { EMPTY_PROFILE_FILTERS, profileOpportunityChip, resolveProfileOpportunityFilters, type FiltersData } from "./profileFilters";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import { FilterModal } from "./ProfileFilterModal";
import { ACTIVITY_TAG_TABS, ActivityTagChips, OPPORTUNITY_TYPE_TABS, OpportunityTypeChips, type OpportunityTypeFilter } from "./profileTabChips";
import { type ProfileDescriptionTabsProps } from "./ProfileDescriptionTabs";

/** The opportunities a profile organised, attended or sponsored. */
export default function OpportunityTabs({
  isVolunteerTeam,
  isPublicProfile = false,
  user_id,
  isVolunteer = false,
}: ProfileDescriptionTabsProps) {
  const [activeTab, setActiveTab] = useState(
    isVolunteer ? "registered" : "organized"
  );
  const [typeFilter, setTypeFilter] = useState<OpportunityTypeFilter>("all");
  const [activityTag, setActivityTag] = useState("all");
  const [open, setOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const debouncedSearch = useDebouncedValue(searchQuery);
  const user = useAuthStore((s) => s.user);
  const [clearFiltersKey, setClearFiltersKey] = useState(0);
  const [isFilterDirty, setIsFilterDirty] = useState(false);
  const [filters, setFilters] = useState<FiltersData>(EMPTY_PROFILE_FILTERS);
  const formikRef = useRef<{ submitForm: () => Promise<void> } | null>(null);

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

  /*
   * A volunteer team has no Sponsor tab, so if the profile turns out to be one
   * while that tab is selected, fall back to Organizer.
   *
   * Corrected during render rather than from an effect: the fix then lands in
   * the same commit as the change, instead of rendering the sponsored list
   * once — against an API that serves a volunteer team nothing — and
   * re-rendering. Same pattern as the pagination reset in `useCommunity`.
   */
  if (isVolunteerTeam && activeTab === "sponsored") {
    setActiveTab("organized");
  }

  const handleApplyFilters = (newFilters: FiltersData) => {
    setFilters(resolveProfileOpportunityFilters(newFilters));
    setActivityTag(newFilters.profile_activity_tag?.toLowerCase() || "all");
    setTypeFilter(profileOpportunityChip(newFilters.opportunity_type));
    setOpen(false);
  };


  // True while the user has typed but the debounce hasn't fired yet
  const isSearching = searchQuery !== debouncedSearch;

  // The chips win over the filter modal's type when one is picked.
  const typeParam = OPPORTUNITY_TYPE_TABS.find(
    (type) => type.value === typeFilter
  )?.param;

  // Participant / Provider only applies to development activities.
  const isDevelopmentFilter = isVolunteer && !isVolunteerTeam && profileOpportunityChip(typeParam || filters.opportunity_type) === "development";
  const activityTagParam = isDevelopmentFilter
    ? ACTIVITY_TAG_TABS.find((tag) => tag.value === activityTag)?.param
    : undefined;

  // 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);
    setFilters(previous => resolveProfileOpportunityFilters({ ...previous, opportunity_type: OPPORTUNITY_TYPE_TABS.find(item => item.value === value)?.param || "", profile_activity_tag: value === "development" ? previous.profile_activity_tag : "" }));
    if (value !== "development") setActivityTag("all");
  };

  const typedFilters = resolveProfileOpportunityFilters({ ...filters, profile_activity_tag: filters.profile_activity_tag || activityTagParam }, typeParam);

  return (
    <>
      <FilterModal
        open={open}
        onClose={() => setOpen(false)}
        clearFiltersKey={clearFiltersKey}
        formikRef={formikRef}
        isFilterDirty={isFilterDirty}
        setIsFilterDirty={setIsFilterDirty}
        onApply={handleApplyFilters}
        onClear={() => {
          setFilters(EMPTY_PROFILE_FILTERS);
          setTypeFilter("all");
          setActivityTag("all");
          setClearFiltersKey((prev) => prev + 1);
        }}
        filters={filters}
        isEventFilter={false}
        allowDevelopmentRole={isVolunteer && !isVolunteerTeam}
        type
      />

      <div className="relative dotlist-white">
        <div className="flex justify-between items-center 2xl:px-5 px-3 mobilescreen:px-[13px] mobilescreen:block">
          <ProfileTabsBar
            activeTab={activeTab}
            setActiveTab={setActiveTab}
            isVolunteer={isVolunteer}
            isVolunteerTeam={isVolunteerTeam}
          />

          {/* Two chip groups plus the search bar do not fit on one line
              between ~768px and ~1135px, so the row wraps: each group moves to
              the next line whole rather than collapsing. */}
          <div className="flex flex-wrap items-center justify-end gap-3 mobilescreen:justify-start">
            <OpportunityTypeChips
              value={typeFilter}
              onChange={handleTypeFilterChange}
            />
            {isDevelopmentFilter && (
              <ActivityTagChips value={activityTag} onChange={value => { setActivityTag(value); setFilters(previous => ({ ...previous, profile_activity_tag: value === "all" ? "" : value })); }} />
            )}
            <div className="orgsearch shrink-0 mobilescreen:w-full">
              <Searchbar
                onFilterClick={() => setOpen(true)}
                onSearchChange={(value) => setSearchQuery(value)}
                hasActiveFilters={hasAppliedFilters}
                isLoading={isSearching}
                onClearFilters={() => {
                  setFilters(EMPTY_PROFILE_FILTERS);
                  setClearFiltersKey((prev) => prev + 1);
                }}
              />
            </div>
          </div>
        </div>

        {activeTab === "registered" && isVolunteer && (
          <ProfileVolunteerCard
            buttonText={undefined}
            filter_type="registered"
            filters={typedFilters}
            searchQuery={debouncedSearch}
            currentUser={user}
            isPublicProfile={isPublicProfile}
            user_id={user_id}
            type="registered"
            useNewApi
          />
        )}

        {activeTab === "organized" && (
          <ProfileVolunteerCard
            buttonText={undefined}
            filter_type="organized"
            filters={typedFilters}
            searchQuery={debouncedSearch}
            currentUser={user}
            isPublicProfile={isPublicProfile}
            user_id={user_id}
            type="organized"
            useNewApi={isVolunteer}
          />
        )}

        {activeTab === "sponsored" && !isVolunteerTeam && (
          <ProfileVolunteerCard
            buttonText={undefined}
            filter_type="sponsored"
            filters={typedFilters}
            searchQuery={debouncedSearch}
            currentUser={user}
            isPublicProfile={isPublicProfile}
            user_id={user_id}
            type="sponsored"
          />
        )}
      </div>
    </>
  );
}
