"use client";

import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import Button from "@/components/ui/Button";
import Loader from "@/components/ui/Loader";
import { getPublicProfile } from "@/features/profile/services/profileApi";
import { getReadErrorMessage } from "@/lib/api/errors";
import { toNumber } from "@/lib/helpers";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import IndividualProfileView from "./individual/IndividualProfileView";
import {
  fromPublicOrganizationProfile,
  fromPublicProfile,
  fromPublicTeamProfile,
} from "./individual/individualProfile";

import ProfileHeader from "./ProfileHeader";
import BackgroundAndAchievements from "./ProfileAchievements";
import PublicProfileListings from "./PublicProfileListings";
import type { PublicProfileResponse } from "./commonProfileTypes";

export default function CommonProfile({ id }: { id: string }) {
  const { t } = useTranslation();
  const language = useLanguageStore((state) => state.language);
  const currentUserId = useAuthStore((state) => state.user?.id);
  const profileQuery = useQuery({
    queryKey: ["public-profile", id],
    queryFn: () => getPublicProfile(id),
    enabled: Boolean(id),
  });
  const response = profileQuery.data?.data as PublicProfileResponse | undefined;

  if (profileQuery.isLoading) return <Loader />;
  if (profileQuery.isError) {
    return (
      <div role="alert" className="mx-auto max-w-3xl py-24 text-center">
        <p className="mb-6 text-lg text-red-600">
          {getReadErrorMessage(profileQuery.error, language, {
            notFound: t("COMMON.PROFILE_NOT_FOUND"),
            failed: t("COMMON.DETAILS_LOAD_FAILED"),
          })}
        </p>
        <Button size="medium" onClick={() => profileQuery.refetch()}>
          {t("COMMON.RETRY")}
        </Button>
      </div>
    );
  }
  // An account without a public profile (e.g. staff) answers `profile_data: null`.
  if (!response?.profile_data) {
    return (
      <p className="mx-auto max-w-3xl py-24 text-center text-lg text-secondary-102">
        {t("COMMON.PROFILE_NOT_FOUND")}
      </p>
    );
  }

  const profile = response.profile_data;
  // `/public-profile/<id>` is also reachable for your own account (every
  // avatar in the community feed, register lists and leaderboards links here
  // by user id), so ownership is decided by id rather than by route.
  const isOwnProfile =
    currentUserId != null && String(currentUserId) === String(profile.id);
  const isTeam = Boolean(response.is_volunteer_team);
  // Pure volunteers get the volunteer development counter; teams use the
  // organization counter even if ever labelled `volunteer`.
  const isPureVolunteer = response.user_type === "volunteer" && !isTeam;
  const volunteerDevelopmentRaw =
    profile.development_opportunities_count ??
    profile.statistics?.all_time?.total_learn_opportunities ??
    profile.statistics?.all_time?.total_development_opportunities ??
    profile.total_learn_opportunities ??
    profile.total_development_opportunities ??
    profile.learn_opportunities_count ??
    null;

  // Individuals, volunteer teams and (since 2026-10-15) organizations get the
  // redesigned profile, shared with their own view. The page below is left
  // for any other account type the endpoint may answer with.
  const isOrganization = response.user_type === "organization" && !isTeam;
  if (isPureVolunteer || isTeam || isOrganization) {
    return (
      <IndividualProfileView
        key={`${profile.id}-${isOwnProfile}`}
        profile={
          isTeam
            ? fromPublicTeamProfile(response)
            : isOrganization
              ? fromPublicOrganizationProfile(response)
              : fromPublicProfile(response)
        }
        isOwnProfile={isOwnProfile}
      />
    );
  }

  return (
    <div className="border-t border-black opp-itm-shadow">
      <div className="relative mx-auto w-[90%] md:w-[85%] lg:w-[90%] 2xl:w-[75%]">
        <ProfileHeader
          profile={profile}
          badge={response.badge_info}
          userType={response.user_type}
        />
        <BackgroundAndAchievements
          profile={profile}
          userType={response.user_type}
          isVolunteerTeam={isTeam}
        />
        <PublicProfileListings
          key={`${profile.id}-${isOwnProfile}`}
          userId={String(profile.id)}
          userType={response.user_type}
          isVolunteerTeam={isTeam}
          developmentCount={
            isPureVolunteer
              ? volunteerDevelopmentRaw == null
                ? // Older API deployment: no counter to gate on, so keep the
                  // Development chip visible.
                  null
                : toNumber(volunteerDevelopmentRaw)
              : profile.learn_opportunity_organized == null
                ? null
                : toNumber(profile.learn_opportunity_organized)
          }
          isOwnProfile={isOwnProfile}
        />
      </div>
    </div>
  );
}
