"use client";

import {
  Award,
  Building2,
  Calendar as CalendarIcon,
  Camera,
  Check,
  Eye,
  EyeOff,
  FileText,
  Globe,
  Mail,
  Plus,
  SquarePen,
  Trash2,
  X,
} from "lucide-react";
import Image from "next/image";
import { useRef, useState } from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { toast } from "react-hot-toast";

import {
  useUpdatePasswordMutation,
  useUpdateProfileMutation,
  useUploadAttachmentMutation,
} from "@/api/auth.api";
import { useGetCategoryTreeQuery } from "@/api/category.api";
import {
  ISocialMediaLink,
  IUpdateProfileRequest,
  IUserProfile,
} from "@/api/types/auth";
import { parseApiError } from "@/api/utils/error-handler";
import { SOCIAL_LINKS } from "@/components/common/constant";
import { useAppDispatch } from "@/redux/hooks";
import { updateUser } from "@/redux/slices/authSlice";

interface MyAccountProfileProps {
  userProfile: IUserProfile;
  email: string;
}

const toDate = (iso: string | null | undefined): Date | null =>
  iso ? new Date(iso) : null;

const toIsoDateString = (d: Date | null): string | null =>
  d
    ? `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(
        d.getDate(),
      ).padStart(2, "0")}`
    : null;

const formatDate = (d: Date | null): string =>
  d
    ? d.toLocaleDateString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
      })
    : "—";

const isValidUrl = (value: string) => {
  try {
    const u = new URL(value);
    return u.protocol === "http:" || u.protocol === "https:";
  } catch {
    return false;
  }
};

const PLATFORM_DOMAINS: Record<string, string[]> = {
  Facebook: ["facebook.com", "fb.com"],
  LinkedIn: ["linkedin.com"],
  "X(Twitter)": ["twitter.com", "x.com"],
  Instagram: ["instagram.com"],
  Pinterest: ["pinterest.com"],
};

const matchesPlatform = (platform: string, url: string): boolean => {
  const domains = PLATFORM_DOMAINS[platform];
  if (!domains) return true;
  try {
    const host = new URL(url).hostname.toLowerCase().replace(/^www\./, "");
    return domains.some((d) => host === d || host.endsWith(`.${d}`));
  } catch {
    return false;
  }
};

const platformPlaceholder = (platform: string): string => {
  const domain = PLATFORM_DOMAINS[platform]?.[0];
  return domain ? `https://www.${domain}/username` : "https://...";
};

const getInitials = (name: string) => {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  return (
    (
      (parts[0]?.[0] ?? "") +
      (parts.length > 1 ? parts[parts.length - 1][0] : "")
    ).toUpperCase() || "U"
  );
};

interface RankCategory {
  id: number;
  name: string;
  childCategories?: RankCategory[];
}

const findRankName = (
  tree: RankCategory[] | undefined,
  id: string,
): string | undefined => {
  if (!tree || !id) return undefined;
  for (const parent of tree) {
    if (parent.id?.toString() === id) return parent.name;
    for (const child of parent.childCategories ?? []) {
      if (child.id?.toString() === id) return child.name;
    }
  }
  return undefined;
};

const fieldInput =
  "w-full h-[34px]! text-sm border border-coolgray-200 rounded-lg px-3 focus:outline-none focus:ring-2 focus:ring-blue-light bg-white text-coolgray-800";

const MyAccountProfile = ({ userProfile, email }: MyAccountProfileProps) => {
  const dispatch = useAppDispatch();

  const [updateProfile, { isLoading: isSaving }] = useUpdateProfileMutation();
  const [uploadAttachment, { isLoading: isUploading }] =
    useUploadAttachmentMutation();
  const [updatePassword, { isLoading: isUpdatingPassword }] =
    useUpdatePasswordMutation();
  const { data: rankCategories } = useGetCategoryTreeQuery("rank");

  // ── Inline-edit toggles ────────────────────────────────────────────────────
  const [editingProfile, setEditingProfile] = useState(false);
  const [editingBio, setEditingBio] = useState(false);

  // ── Working state ───────────────────────────────────────────────────────────
  const [name, setName] = useState(userProfile.name || "");
  const [selectedRankId, setSelectedRankId] = useState(
    userProfile.rank?.id?.toString() || "",
  );
  const [presentRankSince, setPresentRankSince] = useState<Date | null>(
    toDate(userProfile.presentRankSince),
  );
  const [presentCompany, setPresentCompany] = useState(
    userProfile.presentCompany || "",
  );
  const [presentCompanySince, setPresentCompanySince] = useState<Date | null>(
    toDate(userProfile.presentCompanySince),
  );
  const [aboutMe, setAboutMe] = useState(userProfile.aboutMe || "");
  const [nationality, setNationality] = useState(userProfile.nationality || "");
  const [dob, setDob] = useState<Date | null>(toDate(userProfile.dob));
  const [socialMediaLinks, setSocialMediaLinks] = useState<ISocialMediaLink[]>(
    Array.isArray(userProfile.socialMediaLinks)
      ? userProfile.socialMediaLinks
      : [],
  );
  const [profileImageId, setProfileImageId] = useState<number | undefined>(
    userProfile.profileImage?.id,
  );
  const [previewImage, setPreviewImage] = useState<string | null>(
    userProfile.profileImage?.filePath || null,
  );

  // Last-saved snapshot for the inline-edit (profile + bio) Cancel buttons.
  const [saved, setSaved] = useState({
    name: userProfile.name || "",
    rankId: userProfile.rank?.id?.toString() || "",
    presentRankSince: toDate(userProfile.presentRankSince),
    presentCompany: userProfile.presentCompany || "",
    presentCompanySince: toDate(userProfile.presentCompanySince),
    aboutMe: userProfile.aboutMe || "",
    nationality: userProfile.nationality || "",
  });

  // Password
  const [showCurrentPw, setShowCurrentPw] = useState(false);
  const [showNewPw, setShowNewPw] = useState(false);
  const [showConfirmPw, setShowConfirmPw] = useState(false);
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  const [openPlatformIndex, setOpenPlatformIndex] = useState<number | null>(
    null,
  );

  const fileInputRef = useRef<HTMLInputElement>(null);

  const rankName =
    findRankName(rankCategories as RankCategory[] | undefined, saved.rankId) ||
    userProfile.rank?.name ||
    "—";

  const buildPayload = (
    overrides?: Partial<IUpdateProfileRequest>,
  ): IUpdateProfileRequest => ({
    name: name.trim(),
    profileImageId,
    rankId: selectedRankId ? parseInt(selectedRankId) : undefined,
    dob: toIsoDateString(dob),
    presentRankSince: presentRankSince ? presentRankSince.toISOString() : null,
    presentCompany: presentCompany.trim() || null,
    presentCompanySince: presentCompanySince
      ? presentCompanySince.toISOString()
      : null,
    aboutMe: aboutMe.trim() || null,
    nationality: nationality.trim() || null,
    socialMediaLinks: socialMediaLinks.length > 0 ? socialMediaLinks : null,
    ...overrides,
  });

  // Always sends the full profile so partial card saves never drop other fields.
  const persist = async (
    overrides?: Partial<IUpdateProfileRequest>,
  ): Promise<boolean> => {
    if (!name.trim()) {
      toast.error("Name is required.");
      return false;
    }
    if (!selectedRankId) {
      toast.error("Rank is required.");
      return false;
    }
    // Social-link validation
    for (const link of socialMediaLinks) {
      if (!link.platform.trim()) {
        toast.error("Select a platform for each social link.");
        return false;
      }
      if (!link.url.trim() || !isValidUrl(link.url)) {
        toast.error(`Enter a valid URL for ${link.platform}.`);
        return false;
      }
      if (!matchesPlatform(link.platform, link.url)) {
        toast.error(`Enter a valid ${link.platform} URL.`);
        return false;
      }
    }
    if (dob) {
      if (presentCompanySince && dob >= presentCompanySince) {
        toast.error(
          "Date of Birth must be earlier than Present Company Since.",
        );
        return false;
      }
      if (presentRankSince && dob >= presentRankSince) {
        toast.error("Date of Birth must be earlier than Present Rank Since.");
        return false;
      }
    }

    try {
      const payload = buildPayload(overrides);
      await updateProfile(payload).unwrap();
      dispatch(
        updateUser({
          name: payload.name,
          profileImage: previewImage,
          rankName:
            findRankName(
              rankCategories as RankCategory[] | undefined,
              selectedRankId,
            ) || rankName,
        }),
      );
      setSaved({
        name,
        rankId: selectedRankId,
        presentRankSince,
        presentCompany,
        presentCompanySince,
        aboutMe,
        nationality,
      });
      return true;
    } catch (error) {
      toast.error(parseApiError(error));
      return false;
    }
  };

  const handleAvatar = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const formData = new FormData();
    formData.append("file", file);
    try {
      // 1. Upload the file to get an attachment id.
      const res = await uploadAttachment(formData).unwrap();
      setProfileImageId(res.id);
      setPreviewImage(res.filePath);
      // 2. Persist the new image id via the same update-profile API. This runs
      //    independently of the form-level Save (no name/rank gate) so changing
      //    just the photo always saves, even for incomplete profiles.
      const payload = buildPayload({ profileImageId: res.id });
      await updateProfile(payload).unwrap();
      dispatch(updateUser({ profileImage: res.filePath }));
      toast.success("Photo updated!");
    } catch (error) {
      toast.error(parseApiError(error));
    }
    e.target.value = "";
  };

  // ── Profile card actions ────────────────────────────────────────────────────
  const cancelProfile = () => {
    setName(saved.name);
    setSelectedRankId(saved.rankId);
    setPresentRankSince(saved.presentRankSince);
    setPresentCompany(saved.presentCompany);
    setPresentCompanySince(saved.presentCompanySince);
    setNationality(saved.nationality);
    setEditingProfile(false);
  };
  const saveProfile = async () => {
    const ok = await persist();
    if (ok) {
      setEditingProfile(false);
      toast.success("Profile updated!");
    }
  };

  // ── Bio card actions ─────────────────────────────────────────────────────────
  const cancelBio = () => {
    setAboutMe(saved.aboutMe);
    setEditingBio(false);
  };
  const saveBio = async () => {
    const ok = await persist();
    if (ok) {
      setEditingBio(false);
      toast.success("Bio updated!");
    }
  };

  // ── Additional details (DOB + social) ────────────────────────────────────────
  const addSocialLink = () =>
    setSocialMediaLinks((prev) => [...prev, { platform: "", url: "" }]);
  const updateSocialLink = (
    index: number,
    field: keyof ISocialMediaLink,
    value: string,
  ) =>
    setSocialMediaLinks((prev) =>
      prev.map((l, i) => (i === index ? { ...l, [field]: value } : l)),
    );
  const removeSocialLink = (index: number) =>
    setSocialMediaLinks((prev) => prev.filter((_, i) => i !== index));
  const saveAdditional = async () => {
    const ok = await persist();
    if (ok) toast.success("Details updated!");
  };

  const handleSavePassword = async () => {
    if (!currentPassword.trim())
      return toast.error("Current password is required.");
    if (!newPassword.trim()) return toast.error("New password is required.");
    if (newPassword.length < 8)
      return toast.error("New password must be at least 8 characters.");
    if (newPassword !== confirmPassword)
      return toast.error("New password and confirm password do not match.");
    try {
      await updatePassword({
        currentPassword,
        newPassword,
        confirmNewPassword: confirmPassword,
      }).unwrap();
      toast.success("Password updated successfully!");
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
    } catch (error) {
      toast.error(parseApiError(error));
    }
  };

  const hasAvatar =
    typeof previewImage === "string" && previewImage.trim() !== "";

  return (
    <div className="flex flex-col gap-5">
      {/* ── Profile card ─────────────────────────────────────────────────────── */}
      <div className="bg-white rounded-2xl border border-[#E2E2E2] overflow-hidden">
        {/* Header */}
        <div className="px-6 pt-6 pb-5 flex items-center gap-3 sm:gap-5 border-b border-coolgray-100">
          {/* Avatar (click to upload) */}
          <div
            className="relative flex-shrink-0 cursor-pointer group"
            onClick={() => fileInputRef.current?.click()}
          >
            {hasAvatar ? (
              <Image
                src={previewImage as string}
                alt={saved.name}
                width={80}
                height={80}
                className="h-20 w-20 rounded-full object-cover shadow-sm ring-4 ring-white"
              />
            ) : (
              <div className="h-20 w-20 rounded-full flex items-center justify-center text-white text-2xl font-bold shadow-sm ring-4 ring-white bg-blue-light">
                {getInitials(saved.name)}
              </div>
            )}
            <div className="absolute inset-0 rounded-full bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
              {isUploading ? (
                <div className="animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent" />
              ) : (
                <Camera className="h-5 w-5 text-white" />
              )}
            </div>
            <input
              type="file"
              ref={fileInputRef}
              accept="image/*"
              className="hidden"
              onChange={handleAvatar}
            />
          </div>

          {/* Name + rank / name input */}
          {editingProfile ? (
            <>
              <div className="flex-1 min-w-0">
                <input
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  className="text-lg font-bold text-coolgray-900 border border-coolgray-200 rounded-lg px-3 w-full h-[34px] focus:outline-none focus:ring-2 focus:ring-blue-light"
                />
              </div>
              <div className="shrink-0 flex items-center gap-2">
                <button
                  type="button"
                  onClick={cancelProfile}
                  className="flex items-center gap-1 px-2 sm:px-3 h-[34px] rounded-lg border border-coolgray-200 text-sm text-coolgray-500 hover:bg-coolgray-50 transition-colors"
                >
                  <X className="h-3.5 w-3.5" />
                  <span className="hidden sm:inline">Cancel</span>
                </button>
                <button
                  type="button"
                  onClick={saveProfile}
                  disabled={isSaving}
                  className="flex items-center gap-1 px-2 sm:px-3 h-[34px] rounded-lg bg-blue-light hover:bg-blue-light-hover text-white text-sm font-semibold transition-colors disabled:opacity-50"
                >
                  <Check className="h-3.5 w-3.5" />
                  <span className="hidden sm:inline">
                    {isSaving ? "Saving..." : "Save"}
                  </span>
                </button>
              </div>
            </>
          ) : (
            <>
              <div className="flex-1 min-w-0">
                <p className="text-lg font-bold text-coolgray-900 truncate">
                  {saved.name}
                </p>
                <p className="text-sm text-coolgray-500 mt-0.5 truncate">
                  {rankName}
                </p>
              </div>
              <button
                type="button"
                onClick={() => setEditingProfile(true)}
                className="flex items-center gap-1.5 px-3 h-[34px] rounded-lg border border-coolgray-200 text-sm text-coolgray-600 hover:bg-coolgray-50 transition-colors"
              >
                <SquarePen className="h-3.5 w-3.5" />
                Edit
              </button>
            </>
          )}
        </div>

        {/* Fields */}
        <div className="px-6 py-4 space-y-4">
          {/* Email */}
          <div className="flex items-center gap-3 pb-4 border-b border-coolgray-100">
            <div className="h-8 w-8 rounded-lg bg-coolgray-50 flex items-center justify-center flex-shrink-0">
              <Mail className="h-4 w-4 text-coolgray-400" />
            </div>
            <div className="min-w-0 flex-1">
              <p className="text-[11px] text-coolgray-400 font-semibold uppercase tracking-wide mb-0.5">
                Email
              </p>
              <p className="text-sm font-semibold text-coolgray-800 break-all">
                {email}
              </p>
            </div>
          </div>

          {/* Nationality */}
          <div className="flex items-center gap-3 pb-4 border-b border-coolgray-100">
            <div className="h-8 w-8 rounded-lg bg-coolgray-50 flex items-center justify-center flex-shrink-0">
              <Globe className="h-4 w-4 text-coolgray-400" />
            </div>
            <div className="min-w-0 flex-1">
              <p className="text-[11px] text-coolgray-400 font-semibold uppercase tracking-wide mb-0.5">
                Nationality
              </p>
              {editingProfile ? (
                <input
                  value={nationality}
                  onChange={(e) => setNationality(e.target.value)}
                  placeholder="Nationality"
                  className={`${fieldInput} mt-1`}
                />
              ) : (
                <p className="text-sm font-semibold text-coolgray-800">
                  {saved.nationality || "—"}
                </p>
              )}
            </div>
          </div>

          {/* Rank + Present Rank Since */}
          <div className="flex items-start gap-3 pb-4 border-b border-coolgray-100">
            <div className="h-8 w-8 rounded-lg bg-coolgray-50 flex items-center justify-center shrink-0 mt-0.5">
              <Award className="h-4 w-4 text-coolgray-400" />
            </div>
            <div className="flex flex-col sm:flex-row gap-4 flex-1 min-w-0">
              <div className="min-w-0 flex-1">
                <p className="text-[11px] text-coolgray-400 font-semibold uppercase tracking-wide mb-0.5">
                  Rank
                </p>
                {editingProfile ? (
                  <select
                    value={selectedRankId}
                    onChange={(e) => setSelectedRankId(e.target.value)}
                    className={`${fieldInput} mt-1`}
                  >
                    <option value="">Choose Rank</option>
                    {(rankCategories as RankCategory[] | undefined)?.map(
                      (parent) => {
                        const kids = parent.childCategories ?? [];
                        return kids.length === 0 ? (
                          <option key={parent.id} value={String(parent.id)}>
                            {parent.name}
                          </option>
                        ) : (
                          <optgroup key={parent.id} label={parent.name}>
                            {kids.map((c) => (
                              <option key={c.id} value={String(c.id)}>
                                {c.name}
                              </option>
                            ))}
                          </optgroup>
                        );
                      },
                    )}
                  </select>
                ) : (
                  <p className="text-sm font-semibold text-coolgray-800">
                    {rankName}
                  </p>
                )}
              </div>
              <div className="min-w-0 flex-1">
                <p className="text-[11px] text-coolgray-400 font-semibold uppercase tracking-wide mb-0.5">
                  Present Rank Since
                </p>
                {editingProfile ? (
                  <div className="relative mt-1">
                    <DatePicker
                      selected={presentRankSince}
                      onChange={(date: Date | null) =>
                        setPresentRankSince(date)
                      }
                      dateFormat="MMM d, yyyy"
                      placeholderText="Select date"
                      maxDate={new Date()}
                      showYearDropdown
                      showMonthDropdown
                      dropdownMode="select"
                      wrapperClassName="w-full"
                      className={`${fieldInput} pr-10`}
                    />
                    <CalendarIcon
                      size={16}
                      className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-coolgray-400"
                    />
                  </div>
                ) : (
                  <p className="text-sm font-semibold text-coolgray-800">
                    {formatDate(saved.presentRankSince)}
                  </p>
                )}
              </div>
            </div>
          </div>

          {/* Company + Present Company Since */}
          <div className="flex items-start gap-3">
            <div className="h-8 w-8 rounded-lg bg-coolgray-50 flex items-center justify-center shrink-0 mt-0.5">
              <Building2 className="h-4 w-4 text-coolgray-400" />
            </div>
            <div className="flex flex-col sm:flex-row gap-4 flex-1 min-w-0">
              <div className="min-w-0 flex-1">
                <p className="text-[11px] text-coolgray-400 font-semibold uppercase tracking-wide mb-0.5">
                  Company
                </p>
                {editingProfile ? (
                  <input
                    value={presentCompany}
                    onChange={(e) => setPresentCompany(e.target.value)}
                    placeholder="Company"
                    className={`${fieldInput} mt-1`}
                  />
                ) : (
                  <p className="text-sm font-semibold text-coolgray-800">
                    {saved.presentCompany || "—"}
                  </p>
                )}
              </div>
              <div className="min-w-0 flex-1">
                <p className="text-[11px] text-coolgray-400 font-semibold uppercase tracking-wide mb-0.5">
                  Present Company Since
                </p>
                {editingProfile ? (
                  <div className="relative mt-1">
                    <DatePicker
                      selected={presentCompanySince}
                      onChange={(date: Date | null) =>
                        setPresentCompanySince(date)
                      }
                      dateFormat="MMM d, yyyy"
                      placeholderText="Select date"
                      maxDate={new Date()}
                      showYearDropdown
                      showMonthDropdown
                      dropdownMode="select"
                      wrapperClassName="w-full"
                      className={`${fieldInput} pr-10`}
                    />
                    <CalendarIcon
                      size={16}
                      className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-coolgray-400"
                    />
                  </div>
                ) : (
                  <p className="text-sm font-semibold text-coolgray-800">
                    {formatDate(saved.presentCompanySince)}
                  </p>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ── Bio card ─────────────────────────────────────────────────────────── */}
      <div className="bg-white rounded-2xl border border-[#E2E2E2] p-6">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <FileText className="h-4 w-4 text-coolgray-400" />
            <h3 className="text-sm font-bold text-coolgray-700 uppercase tracking-wide">
              Bio
            </h3>
          </div>
          {editingBio ? (
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={cancelBio}
                className="flex items-center gap-1 px-3 h-[34px] rounded-lg border border-coolgray-200 text-sm text-coolgray-500 hover:bg-coolgray-50 transition-colors"
              >
                <X className="h-3.5 w-3.5" />
                Cancel
              </button>
              <button
                type="button"
                onClick={saveBio}
                disabled={isSaving}
                className="flex items-center gap-1 px-3 h-[34px] rounded-lg bg-blue-light hover:bg-blue-light-hover text-white text-sm font-semibold transition-colors disabled:opacity-50"
              >
                <Check className="h-3.5 w-3.5" />
                {isSaving ? "Saving..." : "Save"}
              </button>
            </div>
          ) : (
            <button
              type="button"
              onClick={() => setEditingBio(true)}
              className="flex items-center gap-1.5 px-3 h-[34px] rounded-lg border border-coolgray-200 text-sm text-coolgray-600 hover:bg-coolgray-50 transition-colors"
            >
              <SquarePen className="h-3.5 w-3.5" />
              Edit
            </button>
          )}
        </div>
        {editingBio ? (
          <textarea
            value={aboutMe}
            onChange={(e) => setAboutMe(e.target.value)}
            rows={5}
            className="w-full text-sm border border-coolgray-200 rounded-xl px-3.5 py-2.5 resize-none focus:outline-none focus:ring-2 focus:ring-blue-light text-coolgray-700"
          />
        ) : (
          <p className="text-sm text-coolgray-600 leading-relaxed whitespace-pre-line">
            {saved.aboutMe || "No bio added yet."}
          </p>
        )}
      </div>

      {/* ── Additional details: Date of Birth + Social Links ─────────────────── */}
      <div className="bg-white rounded-2xl border border-[#E2E2E2] p-6 space-y-5">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-bold text-coolgray-700 uppercase tracking-wide">
            Additional Details
          </h3>
          <button
            type="button"
            onClick={saveAdditional}
            disabled={isSaving}
            className="flex items-center gap-1 px-3 h-[34px] rounded-lg bg-blue-light hover:bg-blue-light-hover text-white text-sm font-semibold transition-colors disabled:opacity-50 text-nowrap"
          >
            <Check className="h-3.5 w-3.5" />
            {isSaving ? "Saving..." : "Save Changes"}
          </button>
        </div>

        {/* Date of Birth */}
        <div className="flex flex-col gap-2 max-w-[320px]">
          <label className="text-[11px] text-coolgray-400 font-semibold uppercase tracking-wide mb-0.5">
            Date of Birth
          </label>
          <div className="relative">
            <DatePicker
              selected={dob}
              onChange={(date: Date | null) => setDob(date)}
              dateFormat="MMM d, yyyy"
              placeholderText="Select date"
              maxDate={new Date()}
              showYearDropdown
              showMonthDropdown
              dropdownMode="select"
              wrapperClassName="w-full"
              className={`${fieldInput} pr-10`}
            />
            <CalendarIcon
              size={16}
              className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-coolgray-400"
            />
          </div>
        </div>

        {/* Social Media Links */}
        <div className="flex flex-col gap-3">
          <div className="flex items-end justify-between ">
            <label className="text-[11px] text-coolgray-400 font-semibold uppercase tracking-wide mb-0.5">
              Social Media Links
            </label>
            <button
              type="button"
              onClick={addSocialLink}
              disabled={socialMediaLinks.length >= SOCIAL_LINKS.length}
              className="flex items-center gap-1.5 px-3 h-[34px] rounded-lg bg-blue-light hover:bg-blue-light-hover text-white text-sm font-semibold transition-all disabled:opacity-40 disabled:cursor-not-allowed"
            >
              <Plus size={16} />
              Add Link
            </button>
          </div>

          {socialMediaLinks.length === 0 ? (
            <p className="text-coolgray-500 text-sm">
              No social media links added yet.
            </p>
          ) : (
            <div className="flex flex-col gap-3">
              {socialMediaLinks.map((link, index) => (
                <div
                  key={index}
                  className="flex flex-col sm:flex-row gap-3 items-start"
                >
                  <div className="flex-1 w-full lg:flex-none lg:w-[146px] relative">
                    <div
                      className={`flex items-center h-[34px] px-3 rounded-lg border bg-white transition-all cursor-pointer ${
                        openPlatformIndex === index
                          ? "border-blue-light"
                          : "border-coolgray-200"
                      }`}
                      onClick={() =>
                        setOpenPlatformIndex(
                          openPlatformIndex === index ? null : index,
                        )
                      }
                    >
                      <span
                        className={`flex-1 text-sm font-medium ${link.platform ? "text-coolgray-800" : "text-coolgray-400"}`}
                      >
                        {link.platform || "Select platform"}
                      </span>
                    </div>
                    {openPlatformIndex === index && (
                      <>
                        <div
                          className="fixed inset-0 z-40"
                          onClick={() => setOpenPlatformIndex(null)}
                        />
                        <div className="absolute top-full left-0 w-full mt-1 bg-white rounded-lg border border-coolgray-200 shadow-lg z-50 overflow-hidden">
                          {SOCIAL_LINKS.map((s) => {
                            const taken = socialMediaLinks.some(
                              (l, i) =>
                                i !== index && l.platform === s.platform,
                            );
                            return (
                              <div
                                key={s.platform}
                                onClick={() => {
                                  if (taken) return;
                                  updateSocialLink(
                                    index,
                                    "platform",
                                    s.platform,
                                  );
                                  setOpenPlatformIndex(null);
                                }}
                                className={`px-3 py-2 text-sm transition-colors ${
                                  taken
                                    ? "text-coolgray-300 cursor-not-allowed"
                                    : link.platform === s.platform
                                      ? "bg-blue-light text-white cursor-pointer"
                                      : "text-coolgray-700 hover:bg-blue-light/10 hover:text-blue-light cursor-pointer"
                                }`}
                              >
                                {s.platform}
                              </div>
                            );
                          })}
                        </div>
                      </>
                    )}
                  </div>
                  <input
                    type="url"
                    value={link.url}
                    onChange={(e) =>
                      updateSocialLink(index, "url", e.target.value)
                    }
                    placeholder={
                      link.platform
                        ? platformPlaceholder(link.platform)
                        : "https://..."
                    }
                    className={`${fieldInput} flex-1 min-h-[34px]!`}
                  />
                  <button
                    type="button"
                    onClick={() => removeSocialLink(index)}
                    className="h-[34px] w-[34px] flex items-center justify-center rounded-lg border border-coolgray-200 text-red-500 hover:bg-red-50 hover:border-red-300 transition-all shrink-0"
                    aria-label="Remove social link"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* ── Password card ────────────────────────────────────────────────────── */}
      <div className="bg-white rounded-2xl border border-[#E2E2E2] p-6 space-y-5">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-bold text-coolgray-700 uppercase tracking-wide">
            Password
          </h3>
          <button
            type="button"
            onClick={handleSavePassword}
            disabled={isUpdatingPassword}
            className="flex items-center gap-1 px-3 h-[34px] rounded-lg bg-blue-light hover:bg-blue-light-hover text-white text-sm font-semibold transition-colors disabled:opacity-50"
          >
            <Check className="h-3.5 w-3.5" />
            {isUpdatingPassword ? "Saving..." : "Update Password"}
          </button>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {[
            {
              label: "Current Password",
              value: currentPassword,
              set: setCurrentPassword,
              show: showCurrentPw,
              toggle: () => setShowCurrentPw((v) => !v),
            },
            {
              label: "New Password",
              value: newPassword,
              set: setNewPassword,
              show: showNewPw,
              toggle: () => setShowNewPw((v) => !v),
            },
            {
              label: "Confirm New Password",
              value: confirmPassword,
              set: setConfirmPassword,
              show: showConfirmPw,
              toggle: () => setShowConfirmPw((v) => !v),
            },
          ].map((f) => (
            <div key={f.label} className="flex flex-col gap-2">
              <label className="text-[11px] text-coolgray-400 font-semibold uppercase tracking-wide mb-0.5">
                {f.label}
              </label>
              <div className="relative">
                <input
                  type={f.show ? "text" : "password"}
                  value={f.value}
                  onChange={(e) => f.set(e.target.value)}
                  className={`${fieldInput} pr-11`}
                />
                <button
                  type="button"
                  onClick={f.toggle}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-coolgray-400 hover:text-coolgray-600 transition-colors"
                >
                  {f.show ? <EyeOff size={16} /> : <Eye size={16} />}
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default MyAccountProfile;
