"use client";

import type { ProfileDirectoryItem } from "@/features/profile/profileDirectoryRecord";
import type { ApiResponse } from "@/lib/api/types";
import MoreProfileFilterModal from "./MoreProfileFilterModal";
import { TABS } from "./useMoreProfile";
import { ProfileCard } from "./MoreProfileCard";
import Searchbar from "@/components/ui/Searchbar";
import ListingHeader from "@/components/shared/ListingHeader";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/Tabs";
import { SponsorsClient } from "@/features/home";
import Loader from "@/components/ui/Loader";
import QueryErrorNotice from "@/components/shared/QueryErrorNotice";
import { useTranslation } from "react-i18next";
import { useMoreProfile } from "./useMoreProfile";

/**
 * One directory row.
 *
 * `ProfileDirectoryItem` — the transcription of
 * `WebsiteProfileListItemResource` — rather than the local shape this used to
 * declare, which claimed guarantees the resource does not make: `nickname`,
 * `first_name`, `last_name` and `user_type` were all `string` where every one
 * of them is nullable, and it listed `first_name`/`last_name` unconditionally
 * although the **volunteer** branch omits those keys entirely.
 *
 * The three buckets do not share one row shape: volunteers get
 * `VolunteerDirectoryItem`, organizations and volunteer *teams* get
 * `OrganizationDirectoryItem`. Narrow before reading a name.
 */
export type UserProfile = ProfileDirectoryItem;

export type Bucket = "volunteer" | "volunteer_team" | "organization";

export interface ProfilesListParams {
  page: number;
  limit: number;
  search: string;
  name: string;
  /** `users.username` (backend `1983649`); `nickname` matches the display nickname instead. */
  username: string;
}

/**
 * Shape shared by `/profiles/volunteers|organizations|volunteer-teams/` — a
 * flat array with the standard envelope `meta.pagination`.
 *
 * The standard `ApiResponse`, rather than a hand-written subset of it: the
 * local version declared `data?` optional, which hid that these three
 * endpoints always answer through `ApiResponse::paginated` and so always carry
 * both `data` and `meta.pagination`. (`GET /all-profiles/` is the one that
 * does not — see `AllProfilesPayload`.)
 */
export type ProfilesListResponse = ApiResponse<UserProfile[]>;

/**
 * The three former standalone list pages (`/volunteer-profiles-list`,
 * `/volunteer-team-profiles-list`, `/entities-profiles-list`) merged into one
 * page with an in-page tab switcher — the old routes now redirect here with
 * `?tab=`. Switching tabs keeps the current search/filters and swaps which
 * bucket's endpoint drives the grid below.
 */
export default function MoreProfile() {
  const { t } = useTranslation();
  const {
    hasNextPage,
    isError, error, refetch,
    profileLoading,
    isFetching,
    isFetchingNextPage,
    activeBucket,
    searchQuery,
    setSearchQuery,
    open,
    setOpen,
    clearFiltersKey,
    setClearFiltersKey,
    isFilterDirty,
    setIsFilterDirty,
    isFilterEmpty,
    setIsFilterEmpty,
    filters,
    setFilters,
    hasAppliedFilters,
    allProfiles,
    hasLoadedOnce,
    sentinelRef,
    isPendingNextPage,
    handleTabChange,
  } = useMoreProfile();

  if (profileLoading && allProfiles.length === 0 && !hasLoadedOnce) {
    return <Loader />;
  }

  const isSwitchingBucket = isFetching && allProfiles.length === 0;
  const hasNoProfiles = allProfiles.length === 0 && !isFetching;

  return (
    <>
      <div className="border-t border-[#000] opp-itm-shadow">
        <div className="2xl:px-5 px-3 mobilescreen:px-[13px] 2xl:w-[75%] laptopmain:w-[83%] laptop:w-[78%] laptopitm:w-[85%] lg:w-[90%] md:w-[85%] w-[90%] mx-auto py-5 md:py-6 relative">
          <MoreProfileFilterModal
            open={open}
            setOpen={setOpen}
            filters={filters}
            clearFiltersKey={clearFiltersKey}
            isFilterDirty={isFilterDirty}
            setIsFilterDirty={setIsFilterDirty}
            isFilterEmpty={isFilterEmpty}
            setIsFilterEmpty={setIsFilterEmpty}
            onApply={(values) => {
              setFilters(values);
              setOpen(false);
            }}
            onClear={() => {
              setFilters({ name: "", nickname: "", user_type: "" });
              setClearFiltersKey((prev) => prev + 1);
            }}
          />

          <ListingHeader title={t("COMMON.PROFILES")}>
            <div className="w-full sm:w-[300px] lg:w-[340px]">
          <Searchbar
            showFilterIcon
            value={searchQuery}
            onSearchChange={(value) => setSearchQuery(value)}
            onFilterClick={() => setOpen(true)}
            hasActiveFilters={hasAppliedFilters}
            isLoading={isFetching}
            onClearFilters={() => {
              setFilters({ name: "", nickname: "", user_type: "" });
              setClearFiltersKey((prev) => prev + 1);
            }}
          />
            </div>
          </ListingHeader>

          <Tabs
            value={activeBucket}
            onValueChange={handleTabChange}
            className="mt-7 md:mt-10"
          >
            <TabsList className="w-full h-auto flex bg-transparent p-0">
              {TABS.map(({ bucket, labelKey }) => (
                <TabsTrigger
                  key={bucket}
                  value={bucket}
                  className="relative flex-1 rounded-none py-4 text-base md:text-lg font-bold text-primary-5 border-0 border-b-2 border-b-transparent after:pointer-events-none after:absolute after:end-0 after:top-1/2 after:h-3 after:w-px after:-translate-y-1/2 after:bg-primary-5/30 after:content-[''] last:after:hidden data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-primary-5"
                >
                  {t(labelKey)}
                </TabsTrigger>
              ))}
            </TabsList>
          </Tabs>

          <div className="pt-7 md:pt-10">
            {isError && allProfiles.length === 0 ? (
              <QueryErrorNotice error={error} onRetry={() => { void refetch(); }} />
            ) : isSwitchingBucket ? (
              <div className="flex justify-center py-12">
                <Loader inline size="sm" />
              </div>
            ) : hasNoProfiles ? (
              <div className="text-center py-8 text-secondary-102 text-lg font-medium">
                {t("COMMON.NO_PROFILES_AVAILABLE")}
              </div>
            ) : (
              <>
                <div className="listing-card-grid grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 mobilescreen:pb-0">
                  {allProfiles.map((profile) => (
                    <ProfileCard key={profile?.id} profile={profile} />
                  ))}
                </div>
                {(isPendingNextPage || isFetchingNextPage) && (
                  <div className="flex justify-center py-6">
                    <Loader inline size="sm" />
                  </div>
                )}
                {!hasNextPage && allProfiles.length > 0 && !isFetching && (
                  <p className="text-center py-4 text-secondary-102">
                    {t("COMMON.NO_MORE_PROFILES")}
                  </p>
                )}
                <div ref={sentinelRef} />
              </>
            )}
          </div>
        </div>
      </div>

      <div className="border-secondary-100/20 border-t 2xl:pt-[70px] pt-[40px] laptopmain:pt-[50px] laptop:pt-[40px] lg:pt-[40px] mobilescreen:pt-[40px]">
        <SponsorsClient />
      </div>
    </>
  );
}

export { ProfileCard } from "./MoreProfileCard";
