"use client";

import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useTranslation } from "react-i18next";
import {
  FaBriefcase,
  FaGraduationCap,
  FaHandshake,
  FaPenToSquare,
  FaShareNodes,
} from "react-icons/fa6";

import VerifiedBadge from "@/components/ui/VerifiedBadge";
import { occupationOptions } from "@/data/Constants";
import { getDefaultProfileImage, handleShare } from "@/lib/helpers";
import { useLanguageStore } from "@/store/languageStore";
import { badgeImage, badgeLabelKey } from "../commonProfileTypes";
import { sponsorshipProfileLabel, type IndividualProfileData } from "./individualProfile";

const asset = (path: string) => `/assets/${path}`;

/** The domain prefix of the handle under the name. */
const PROFILE_HANDLE_DOMAIN = "joinforsa.net/";

interface ProfileHeaderCardProps {
  profile: IndividualProfileData;
  /** Your own profile gets «تعديل البيانات»; everyone can share. */
  isOwnProfile: boolean;
}

export default function ProfileHeaderCard({ profile, isOwnProfile }: ProfileHeaderCardProps) {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);

  const [failedAvatar, setFailedAvatar] = useState<string | null>(null);
  const defaultAvatar = getDefaultProfileImage(
      profile.kind !== "individual" ? "organization" : profile.genderEn ?? undefined,
      asset("profile/male_profile.svg"),
      asset("profile/female_profile.svg"),
      asset(profile.kind === "individual" ? "profile/male_profile.svg" : "profile/org_profile.svg")
    );
  const profilePicture = profile.profilePic?.trim();
  const avatar = profilePicture && profilePicture !== failedAvatar
    ? profilePicture
    : defaultAvatar;
  const isOrganization = profile.kind === "organization";
  // Every profile displays its earned badge beside the avatar.
  const badgeSrc = badgeImage(profile.badge);

  // PDF p.31: «type – level» of the linked sponsor record; hidden when none.
  const sponsorshipLabel = isOrganization
    ? sponsorshipProfileLabel(profile.sponsorshipProfile, language)
    : "";

  const occupation = occupationOptions.find((option) => option.value === profile.occupation);
  const occupationLabel = occupation
    ? occupation[language === "ar" ? "name_ar" : "name_en"]
    : profile.occupation;
  const OccupationIcon = profile.occupation?.includes("student") ? FaGraduationCap : FaBriefcase;

  // Always the public URL: a private profile redirects to its limited view.
  const shareProfile = () =>
    handleShare(`${window.location.origin}/public-profile/${profile.userId}`, t);

  return (
    <section className="rounded-3xl border border-[#29246D14] bg-white p-6 text-center shadow-[0_4px_16px_rgba(41,36,109,0.06)]">
      <div className="relative mx-auto h-[120px] w-[120px]">
        <Image
          src={avatar}
          onError={() => {
            if (profilePicture && avatar !== defaultAvatar) setFailedAvatar(profilePicture);
          }}
          alt={profile.name || "Profile"}
          fill
          unoptimized
          className="rounded-full border-4 border-primary-5 object-cover"
        />
        {badgeSrc && (
          <span className="absolute -bottom-1 start-0 flex h-10 w-10 items-center justify-center rounded-full ">
            <Image src={badgeSrc} alt={badgeLabelKey(profile.badge) ? t(badgeLabelKey(profile.badge) as string) : profile.badge?.name ?? ""} width={30} height={30} />
          </span>
        )}
      </div>

      {/* One centred column (client, 2026-10-15): name, handle, then each
          pill on its own line — inline pieces used to share the name's line. */}
      <div className="mt-4 flex flex-col items-center gap-1">
        <h1
          className="flex items-center justify-center gap-1.5 text-2xl font-bold text-primary-5"
          dir="auto"
        >
          {profile.name}
          <VerifiedBadge verified={profile.isGovernmentVerified} size={22} />
        </h1>
        {/* Display the platform handle in left-to-right URL order. */}
        {profile.nickname && (
          <p className="text-sm text-secondary-102" dir="ltr">
            {PROFILE_HANDLE_DOMAIN}
            {profile.nickname}
          </p>
        )}

        {(sponsorshipLabel || occupationLabel) && (
          <div className="mt-2 flex flex-col items-center gap-2">
            {sponsorshipLabel && (
              <span
                className="inline-flex items-center gap-1.5 rounded-full border border-[#29246D26] bg-[#29246D0A] px-3 py-0.5 text-xs font-semibold text-primary-5"
                title={t("COMMON.SPONSORSHIP_TYPE")}
              >
                <FaHandshake aria-hidden />
                <span className="sr-only">{t("COMMON.SPONSORSHIP_TYPE")}: </span>
                {sponsorshipLabel}
              </span>
            )}
            {/* {profile.licenseNumber && (
              <span className="inline-flex items-center gap-2 rounded-full border border-[#29246D26] px-4 py-1 text-sm text-primary-5">
                <FaCircleCheck aria-hidden />
                {t("COMMON.LICENSE_NUMBER_LABEL")}: <span dir="ltr">{profile.licenseNumber}</span>
              </span>
            )} */}
            {occupationLabel && (
              <span className="inline-flex items-center gap-2 rounded-full border border-[#29246D26] px-4 py-1 text-sm text-primary-5">
                <OccupationIcon aria-hidden />
                {occupationLabel}
              </span>
            )}
          </div>
        )}
      </div>

      {/* Icons only (client, 2026-10-15); the label stays as the accessible
          name and the hover title. */}
      <div className="mt-5 flex items-center justify-center gap-3">
        {isOwnProfile && (
          <Link
            href="/account-information"
            aria-label={t("COMMON.EDIT_PROFILE_DATA")}
            title={t("COMMON.EDIT_PROFILE_DATA")}
            className="flex h-12 w-12 items-center justify-center rounded-full bg-primary-5 text-white transition hover:opacity-90"
          >
            <FaPenToSquare size={18} aria-hidden />
          </Link>
        )}
        <button
          type="button"
          onClick={shareProfile}
          aria-label={t("COMMON.SHARE_PROFILE")}
          title={t("COMMON.SHARE_PROFILE")}
          className="flex h-12 w-12 items-center justify-center rounded-full border border-[#29246D26] bg-[#29246D0A] text-primary-5 transition hover:bg-[#29246D14]"
        >
          <FaShareNodes size={18} aria-hidden />
        </button>
      </div>
    </section>
  );
}
