"use client";

import { useTranslation } from "react-i18next";
import Searchbar from "@/components/ui/Searchbar";
import { ActivityTagChips } from "./ProfileDescriptionTabs";
import ProfileListingsGrid from "./ProfileListingsGrid";
import ProfileListingsFilterModal from "./ProfileListingsFilterModal";
import { usePublicProfileListings } from "./usePublicProfileListings";
import { OPPORTUNITY_TYPE_TABS, type PublicProfileResponse } from "./commonProfileTypes";

/** The tabbed listings: opportunities, events and certificates. */
export default function PublicProfileListings({
  userId,
  userType,
  isVolunteerTeam,
  developmentCount,
  isOwnProfile,
}: {
  userId: string;
  userType: PublicProfileResponse["user_type"];
  isVolunteerTeam: boolean;
  /** Drives whether the "Sponsor" tag appears — see the note on its button. */
  /**
   * Development opportunities this profile organised. `null` when the profile
   * has no such counter (volunteers), in which case the chip always shows.
   */
  developmentCount: number | null;
  /**
   * Certificates are private to their owner: the tab, its grid and the fetch
   * behind it only exist when the signed-in user is looking at their own
   * profile. It is false on every other profile, where nothing about the
   * certificates is requested or rendered.
   */
  isOwnProfile: boolean;
}) {
  const { t } = useTranslation();
  const {
    section, setSection, mode, setMode, typeFilter, handleTypeFilterChange,
    activityTag, setActivityTag, search, setSearch, deferredSearch,
    filterOpen, setFilterOpen, filters, setFilters, clearFiltersKey,
    isFilterDirty, setIsFilterDirty, filterFormRef, hasActiveFilters,
    clearFilters, isDevelopmentFilter, eventsMode, items, certificates,
    loading, sections, error, retry, hasMore, loadingMore, loadMore,
  } = usePublicProfileListings({ userId, userType, isVolunteerTeam, isOwnProfile });

  return (
    <section className="pb-[50px]">
      <ProfileListingsFilterModal
        filterOpen={filterOpen}
        setFilterOpen={setFilterOpen}
        filters={filters}
        setFilters={setFilters}
        clearFiltersKey={clearFiltersKey}
        isFilterDirty={isFilterDirty}
        setIsFilterDirty={setIsFilterDirty}
        filterFormRef={filterFormRef}
        clearFilters={clearFilters}
        section={section}
        mode={mode}
        isIndividual={userType === "volunteer" && !isVolunteerTeam}
      />
      <div className="flex gap-[38px] px-3 2xl:px-5 xss:gap-2">
        {sections.map((tab) => (
          <button
            key={tab.value}
            type="button"
            onClick={() => {
              setSection(tab.value);
              setMode("organized");
              handleTypeFilterChange("all");
              // Opportunity and event filters don't share the same choices.
              clearFilters();
            }}
            className={`relative rounded-t-[20px] border border-primary-5 px-6 py-4 text-xl font-bold text-primary-5 ${
              section === tab.value ? "border-b-white bg-white" : "bg-[#D2D8F6]"
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>
      <div className="border-t border-primary-5 px-3 pt-6 2xl:px-5">
        {section !== "certificates" && (
          <div className="mb-8 flex items-center justify-between gap-6 mobilescreen:flex-col">

            {/* 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 w-full flex-wrap items-center justify-between gap-3 mobilescreen:w-full mobilescreen:justify-start">
              {/* All / Volunteer / Development — events are one type already */}
              {section === "opportunities" && (
                <div className="flex shrink-0 flex-wrap gap-2">
                  {OPPORTUNITY_TYPE_TABS.filter(
                    // A zero development counter hides its counter card, so the
                    // chip that would filter to an empty list goes too. `null`
                    // means the profile has no such counter — keep the chip.
                    (type) =>
                      type.value !== "development" ||
                      developmentCount === null ||
                      developmentCount > 0
                  ).map((type) => (
                    <button
                      key={type.value}
                      type="button"
                      onClick={() => handleTypeFilterChange(type.value)}
                      className={`rounded-full border border-primary-5 px-4 py-2 text-sm font-bold whitespace-nowrap ${
                        typeFilter === type.value
                          ? "bg-primary-5 text-white"
                          : "bg-white text-primary-5"
                      }`}
                    >
                      {t(type.labelKey)}
                    </button>
                  ))}
                </div>
              )}
              {/* Participant / Provider is a development-only split. */}
              {section === "opportunities" && isDevelopmentFilter && (
                <ActivityTagChips
                  value={activityTag}
                  onChange={setActivityTag}
                />
              )}
              {/*
                Events subfilter mirrors the own profile's MyEventsTabs:
                volunteers never reach here (no Events tab), teams get
                Organizer only, entities get Organizer + Sponsor. `mode`
                already drives the `organized_events` / `sponsored_events`
                query above — these buttons are the only writer.
              */}
              {section === "events" && (
                <div className="flex shrink-0 flex-wrap gap-2">
                  <button
                    type="button"
                    onClick={() => setMode("organized")}
                    className={`rounded-full border border-primary-5 px-4 py-2 text-sm font-bold whitespace-nowrap ${
                      eventsMode === "organized"
                        ? "bg-primary-5 text-white"
                        : "bg-white text-primary-5"
                    }`}
                  >
                    {t("COMMON.ORGANIZER_TAG")}
                  </button>
                  {!isVolunteerTeam && (
                    <button
                      type="button"
                      onClick={() => setMode("sponsored")}
                      className={`rounded-full border border-primary-5 px-4 py-2 text-sm font-bold whitespace-nowrap ${
                        eventsMode === "sponsored"
                          ? "bg-primary-5 text-white"
                          : "bg-white text-primary-5"
                      }`}
                    >
                      {t("COMMON.SPONSOR")}
                    </button>
                  )}
                </div>
              )}
              <div className="shrink-0 mobilescreen:w-full">
                <Searchbar
                  value={search}
                  onSearchChange={setSearch}
                  onFilterClick={() => setFilterOpen(true)}
                  hasActiveFilters={hasActiveFilters}
                  onClearFilters={clearFilters}
                  isLoading={search !== deferredSearch}
                />
              </div>
            </div>
          </div>
        )}
        <ProfileListingsGrid
          loading={loading}
          section={section}
          certificates={certificates}
          items={items}
          error={error}
          retry={retry}
          hasMore={hasMore}
          loadingMore={loadingMore}
          loadMore={loadMore}
        />
      </div>
    </section>
  );
}
