"use client";

import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { getAllOpportunities } from "@/features/opportunities/services/opportunities";


import { profileTabs, type IndividualProfileData, type ProfileTab } from "./individualProfile";
import ProfileCertificatesTab from "./ProfileCertificatesTab";
import ProfileEventsTab from "./ProfileEventsTab";
import ProfileHeaderCard from "./ProfileHeaderCard";
import ProfileInterestChips from "./ProfileInterestChips";
import ProfileOpportunitiesTab from "./ProfileOpportunitiesTab";
import ProfileSocialRow from "./ProfileSocialRow";
import ProfileStatTiles from "./ProfileStatTiles";
import QuietModeCard from "./QuietModeCard";

interface IndividualProfileViewProps {
  profile: IndividualProfileData;
  isOwnProfile: boolean;
}

/**
 * The client's redesigned profile (2026-09-26) for individuals and volunteer
 * teams, used for both your own profile and the public one. Organizations
 * joined on 2026-10-15 with their own design: a team's layout, plus a
 * sponsorships tile and «منظم / راعي» in each tab.
 *
 * Tabs (`profileTabs`): an individual gets Opportunities + Certificates (your
 * own profile only — `/user-certificates/` answers for the caller whatever id
 * it is given); an organization gets Opportunities + Events; a volunteer team
 * Opportunities only — teams publish no events (client answer X2).
 */
export default function IndividualProfileView({ profile, isOwnProfile }: IndividualProfileViewProps) {
  const { t } = useTranslation();
  const [tab, setTab] = useState<ProfileTab>("opportunities");
  const { data: hasEvents } = useQuery({
    queryKey: ["profile-events", "availability", profile.userId, isOwnProfile],
    enabled: profile.kind === "organization",
    queryFn: async () => {
      // Check both relations without search/status filters: an empty filtered
      // list must never hide a profile's Events tab.
      const results = await Promise.all(
        ["organized_events", "sponsored_events"].map((filter_type) =>
          getAllOpportunities({
            filter_type,
            user_id: isOwnProfile ? undefined : profile.userId,
            page: 1,
            limit: 1,
          }),
        ),
      );
      return results.some((result) => result.data.length > 0);
    },
  });
  const tabs = profileTabs(profile.kind, isOwnProfile).filter(
    ([value]) => value !== "events" || hasEvents !== false,
  );
  const activeTab = tabs.some(([value]) => value === tab) ? tab : "opportunities";

  return (
    <div className="border-t border-[#000] bg-[#F7F7FB]">
      {/* Stacked on phones, as designed; on large screens the identity column
          sits beside the tabs so the card grid has room. */}
      <div className="mx-auto grid w-full xl:px-10 gap-4 px-4 py-8 lg:grid-cols-[360px_minmax(0,1fr)] lg:items-start max-w-[1740px] ">
        {/* Pinned under the sticky header on large screens, so the page
            scroll moves only the card grid (client, 2026-10-19). A column
            taller than the screen scrolls inside itself. On phones it stacks
            above the tabs and scrolls with the page. */}
        <div className="flex flex-col gap-4 lg:sticky lg:top-[96px] lg:max-h-[calc(100vh-112px)] lg:overflow-y-auto lg:[scrollbar-width:none]">
          <ProfileHeaderCard profile={profile} isOwnProfile={isOwnProfile} />
          <ProfileStatTiles stats={profile.stats} counterVisibility={profile.counterVisibility} />
          <ProfileSocialRow social={profile.social} />
          <ProfileInterestChips interests={profile.interests} />
          {/* A volunteer's own email preference (client, 2026-10-18). */}
          {isOwnProfile && profile.kind === "individual" && <QuietModeCard />}
        </div>

        <section className="rounded-3xl border border-[#29246D14] bg-white p-4">
          <div className="-mx-4 -mt-4 mb-4 flex gap-1 border-b border-primary-5 px-4 pt-4">
            {tabs.map(([value, labelKey]) => (
              <button
                key={value}
                type="button"
                onClick={() => setTab(value)}
                className={`-mb-px rounded-t-2xl border px-6 py-2 text-sm font-semibold ${
                  activeTab === value
                    ? "border-primary-5 border-b-white bg-white text-primary-5"
                    : "border-transparent bg-[#29246D0F] text-secondary-102"
                }`}
              >
                {t(labelKey)}
              </button>
            ))}
          </div>

          {activeTab === "opportunities" && (
            <ProfileOpportunitiesTab
              userId={profile.userId}
              isOwnProfile={isOwnProfile}
              kind={profile.kind}
              isExpert={profile.isExpert}
              expertOpportunitiesCount={profile.expertOpportunitiesCount}
            />
          )}
          {activeTab === "certificates" && <ProfileCertificatesTab userId={profile.userId} />}
          {activeTab === "events" && profile.kind === "organization" && (
            <ProfileEventsTab
              userId={profile.userId}
              isOwnProfile={isOwnProfile}
              canSponsor
            />
          )}
        </section>
      </div>
    </div>
  );
}
