"use client";

import type React from "react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { Card } from "@/src/components/reusables/ui/card";
import { HeartIcon, Pencil, Save, XIcon } from "lucide-react";
import HobbyIcon from "@/src/components/reusables/ui/hobbyIcon";
import InterestIcon from "@/src/components/reusables/ui/interestIcon";
import AboutMeItem from "@/src/components/reusables/ui/about-me-item";
import PhotoGallery from "@/src/components/reusables/ui/photoGallery";
import ProfilePicture from "@/src/components/reusables/ui/profilePicture";
import { type ChangeEvent, Fragment, useEffect, useRef, useState } from "react";
import { Textarea } from "@/components/ui/textarea";
import { notify } from "@/lib/toastify";
import { MultiSelect } from "../../reusables/ui/multiselect";
import Overlay from "../../reusables/overlay/overlay";
import Edit from "./edit";
import { useRouter } from "next/navigation";
import { UserData } from "@/src/utils/dummy-data/profileData";
import { FormsData, Option } from "@/src/utils/types";
import { cn } from "@/lib/utils";
import { usePathname } from "next/navigation";
import { motion } from "framer-motion";
import AnimatedCounter from "./animatedCounter";
import { useGetHobbiesData } from "@/src/utils/hooks/useGetHobbies";
import { useAppDispatch, useAppSelector } from "@/src/redux/hook";
import {
  resetProfile,
  setAboutMe,
  setCountry,
  setCoverPhoto,
  setHobbies,
  setHouseNumber,
  setInterests,
  setLandmark,
  setLanguages,
  setLGA,
  setPostcode,
  setPreviewSrc,
  setProfilePicture,
  setShortBio,
  setState,
  setStreetName,
  setUserPreferredMatches,
  setUserProfile,
} from "@/src/redux/profileSlice";
import HobbyComponent from "../../reusables/ui/HobbyComponent";
import HobbySkeleton from "../../reusables/ui/HobbySkeleton";
import InterestComponent from "../../reusables/ui/InterestComponent";
import AboutMe from "./AboutMe";
import { useGetUserPreferredMatches } from "@/src/utils/hooks/useGetUserPreferredMatches";
import PreferredMatch from "./PreferredMatch";
import { useGetInputData } from "@/src/utils/hooks/useGetInputData";
import { useInputOptions } from "@/src/utils/functions";
import MultiSelectPopup2, {
  SelectOption,
} from "../../reusables/ui/MultiSelectPopup2";
import LineSkeleton from "../../reusables/ui/LineSkeletonLoader";
import { useGetUserProfile } from "@/src/utils/hooks/useGetUserProfile";
import RequestAddressCheck from "../RequestAddressCheck";
import LoadingSpinner from "../../reusables/ui/LoadingSpinner";
import { useGetUserContact } from "@/src/utils/hooks/useGetContact";
import axiosInstance from "@/lib/axios";
import { Badge } from "@/components/ui/badge";
import { resetMatchupProfile } from "@/src/redux/matchProfileSlice";

interface UserProfilePageProps {
  userData?: Omit<UserData, "id">;
  viewMode?: boolean;
}

type UpdateSection =
  | "bio"
  | "interests"
  | "edit"
  | "match"
  | "hobbies"
  | "name"
  | null;

export default function UserProfilePage({
  userData,
  viewMode = false,
}: UserProfilePageProps) {
  // Create refs for file inputs
  const profilePictureInputRef = useRef<HTMLInputElement>(null);
  const coverPhotoInputRef = useRef<HTMLInputElement>(null);
  const galleryPhotoInputRef = useRef<HTMLInputElement>(null);
  const [galleryPhotos, setGalleryPhotos] = useState<
    { src: string; alt?: string }[]
  >([]);
  const currentPhotoIndexRef = useRef<number | null>(null);
  const [updatesection, setUpdateSection] = useState<UpdateSection>(null);
  const [bioSectionData, setBioSectioData] = useState<string | undefined>();
  const pathname = usePathname();
  const [isBioLoading, setIsBioLoading] = useState(false);

  const inputRef = useRef<HTMLInputElement | null>(null);
  const [selectedPhotoIndex, setSelectedPhotoIndex] = useState<number | null>(
    null
  );

  const dispatch = useAppDispatch();

  const [formData, setFormData] = useState<FormsData>({
    name: "",
    mobileNumber: "",
    dateOfBirth: "",
    gender: "",
    relationship: "",
    physicalAddress: "",
    city: "",
    lga: "",
    landmark: "",
    postalCode: "",
    state: "",
    country: "",
    heightRange: ["150", "190"], // cm
    weightRange: ["50", "100"], // kg
    religion: "",
    maritalStatus: "",
    ethnicity: "",
    genotype: "",
    nationality: "",
    interests: [] as string[],
    hobbies: [] as string[],
    languages: [] as string[],
    relationshipType: [],
    ageRange: ["18", "60"],
  });

  // Index of the photo being updated in gallery
  // const currentPhotoIndexRef = useRef<number>(-1);

  const [liked, setLiked] = useState<boolean>(false);

  const onUpdateUserInfo = (section: string, data?: unknown) => {
    // This would be implemented to update user info
    console.log(`Updating section: ${section}`, data);
  };

  const handleEditSection = (section: UpdateSection) => {
    if (viewMode) return;
    setUpdateSection(section);
    // onUpdateUserInfo(section);
  };

  const handleSaveSection = (section: string) => {
    if (bioSectionData && bioSectionData !== "" && section === "bio") {
      onUpdateUserInfo(section, bioSectionData);
      setUpdateSection(null);
      handleCloseEditSection();
    } else if (
      updatesection &&
      (updatesection === "edit" || updatesection === "match")
    ) {
      onUpdateUserInfo(updatesection, formData);
      setUpdateSection(null);
      handleCloseEditSection();
    } else {
      notify("No change added", false, "no-change-toast", "info");
    }
  };

  const handleCloseEditSection = () => {
    setUpdateSection(null);
  };

  const handleTextAreaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    dispatch(setShortBio(e.target.value));
  };

  const router = useRouter();
  const GoBack = () => {
    router.back();
  };

  const handleFileChange = async (
    e: ChangeEvent<HTMLInputElement>,
    type: "profile" | "cover" | "gallery"
  ) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    const file: any = files[0];

    const previewUrl = URL.createObjectURL(file);

    const userId = localStorage.getItem("userId");
    const token = localStorage.getItem("userToken");

    // Instant preview
    if (type === "profile") {
      dispatch(setProfilePicture(file)); // sets File
      dispatch(setPreviewSrc(previewUrl)); // sets local preview
    }

    if (type === "cover") {
      dispatch(setCoverPhoto(file));
    }

    // Upload to backend only if it's profile or cover
    const field =
      type === "profile" ? "photo" : type === "cover" ? "cover_photo" : "";

    if (!field) return;

    const formData = new FormData();
    formData.append("photo", file);

    try {
      const res = await fetch(
        `${process.env["NEXT_PUBLIC_DEV_URL"]}/users/${userId}/settings/photos/${field}`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
          },
          body: formData,
        }
      );

      if (!res.ok) {
        throw new Error("Upload failed");
      }

      console.log(`picture uploaded to backend successfully`);
    } catch (err) {
      console.error("Failed to upload:", err);
      // Optionally revert preview here or show a toast
    }
  };

  const handleGalleryFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0 || selectedPhotoIndex === null) return;

    const file: any = files[0];
    const previewUrl = URL.createObjectURL(file);

    // Determine which field (photo, photo_1, photo_2, ...)
    const field =
      selectedPhotoIndex === 0 ? "photo" : `photo_${selectedPhotoIndex}`;

    // ✅ 1. Immediately update the preview in UI
    setGalleryPhotos((prev) => {
      const updated = [...prev];

      if (selectedPhotoIndex >= updated.length) {
        updated.push({
          src: previewUrl,
          alt: `New Photo ${selectedPhotoIndex + 1}`,
        });
      } else {
        updated[selectedPhotoIndex] = {
          src: previewUrl,
          alt: `Updated Photo ${selectedPhotoIndex + 1}`,
        };
      }

      return updated;
    });

    // Reset selection immediately
    setSelectedPhotoIndex(null);

    // ✅ 2. Upload in the background
    const imageData = new FormData();
    imageData.append("photo", file);

    const userId = localStorage.getItem("userId");

    try {
      const res = await fetch(
        `${process.env["NEXT_PUBLIC_DEV_URL"]}/users/${userId}/settings/photos/${field}`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${localStorage.getItem("userToken")}`,
          },
          body: imageData,
        }
      );

      if (!res.ok) {
        throw new Error("Failed to upload photo");
      }
    } catch (error) {
      console.error("Upload failed:", error);
      alert("Upload failed. Please try again.");
    }
  };

  const onUploadProfilePicture = () => {
    profilePictureInputRef.current?.click();
  };

  const onUploadPhoto = (index: number) => {
    setSelectedPhotoIndex(index);
    inputRef.current?.click();
  };

  const onUpdateCover = () => {
    coverPhotoInputRef.current?.click();
  };

  const handleEditBio = async () => {
    try {
      setIsBioLoading(true);
      const userId = localStorage.getItem("userId");

      const response = await axiosInstance.patch(
        `/users/${userId}/settings/short_bio`,
        {
          value: shortBio,
        }
      );

      setIsBioLoading(false);
      // setUpdateSection(null);
      handleCloseEditSection();
    } catch (error) {
      console.error("Error updating interests:", error);
    }
  };

  const {
    data: contactData,
    isLoading: contactDataLoading,
    error: contactDataError,
    refetch: refetchContactData,
  } = useGetUserContact();

  useEffect(() => {
    if (contactData?.payload) {
      dispatch(setStreetName(contactData.payload?.street_name));
      dispatch(setHouseNumber(contactData.payload?.house_number));
      dispatch(setLGA(contactData.payload?.lga));
      dispatch(setLandmark(contactData.payload?.land_mark));

      dispatch(setPostcode(contactData.payload?.postal_code));
      dispatch(setCountry(contactData.payload?.nationality));
      dispatch(setState(contactData.payload?.state));
    }
  }, []);

  // const languages = [
  //   "English",
  //   "Spanish",
  //   "French",
  //   "Chinese",
  //   "Japanese",
  //   "Hindu",
  //   "Riqjin",
  //   "Russian",
  //   "Portuguese",
  //   "Latvian",
  //   "Javanese",
  //   "Albanian",
  //   "Jargon",
  //   "Creole",
  //   "Arabic",
  //   "Dravidian",
  //   "Kra-dai",
  //   "Afro-asiatic",
  //   "Indo-european",
  //   "Sino-tibetan",
  //   "Austonesian",
  //   "Niger-congo",
  // ];

  const hobbies = useAppSelector((state) => state.profile.hobbies);
  const interests = useAppSelector((state) => state.profile.interests);
  const languages = useAppSelector((state) => state.profile.languages);
  const aboutMe = useAppSelector((state) => state.profile.aboutMe);
  const userProfile = useAppSelector((state) => state.profile.userProfile);
  const country = useAppSelector((state) => state.profile.country);

  const userPreferredMatches = useAppSelector(
    (state) => state.profile.userPreferredMatches
  );
  const shortBio = useAppSelector((state) => state.profile.shortBio);
  const profilePicture = useAppSelector(
    (state) => state.profile.profilePicture
  );

  const coverPhoto = useAppSelector((state) => state.profile.coverPhoto);

  const [isEditHobbies, setIsEditHobbies] = useState(false);
  const [isEditInterests, setIsEditInterests] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const {
    data: hobbiesData,
    isLoading: hobbiesLoading,
    error: hobbiesError,
    refetch: refetchHobbiesData,
  } = useGetHobbiesData();

  const {
    data: preferredMatchesData,
    isLoading: preferredMatchesLoading,
    error: preferredMatchesError,
  } = useGetUserPreferredMatches();

  useEffect(() => {
    if (hobbiesData) {
      dispatch(setHobbies(hobbiesData?.payload?.hobbies));
      dispatch(setInterests(hobbiesData?.payload?.interest));
      dispatch(setLanguages(hobbiesData?.payload?.language_spoken));
    }
  }, [hobbiesData, dispatch]);

  useEffect(() => {
    if (preferredMatchesData) {
      dispatch(setUserPreferredMatches(preferredMatchesData.payload));
      console.log(preferredMatchesData);
    }
  }, [preferredMatchesData, dispatch]);

  const {
    data: userProfileData,
    isLoading: userProfileLoading,
    error: userProfileError,
    refetch: userProfileRefetch,
  } = useGetUserProfile();

  useEffect(() => {
    if (userProfileData?.payload) {
      try {
        dispatch(setUserProfile(userProfileData?.payload));
        dispatch(setAboutMe(userProfileData?.payload?.about_me));
      } catch (error) {
        console.error("Failed to parse userProfile from localStorage", error);
      }
    }
  }, [userProfileData]);

  console.log({ aboutMe });

  useEffect(() => {
    if (userProfile) {
      dispatch(setShortBio(userProfile?.short_bio));

      const photosFromApi = [
        userProfile.photo,
        userProfile.photo_1,
        userProfile.photo_2,
        userProfile.photo_3,
        userProfile.photo_4,
      ].filter(Boolean) as string[];

      const formatted = photosFromApi.map((src, index) => ({
        src,
        alt: `Gallery image ${index + 1}`,
      }));

      setGalleryPhotos(formatted);
    }
  }, [dispatch, userProfile]);

  // get
  const useInputOptions = (
    keys: string[]
  ): { key: string; options: Option[]; rawValue?: any }[] => {
    return keys.map((key) => {
      const { data } = useGetInputData(key);

      // if nationality → we handle it specially
      if (key === "nationality" && data?.payload?.value) {
        return {
          key,
          options: Object.keys(data.payload.value).map((countryName) => ({
            label: countryName,
            value: countryName.toLowerCase(),
          })),
          rawValue: data.payload.value, // pass raw country object
        };
      }

      if (key === "religion" && data?.payload?.value) {
        return {
          key,
          options: Object.keys(data.payload.value).map((religionName) => ({
            label: religionName,
            value: religionName.toLowerCase(),
            subcategories: data.payload.value[religionName].denominations.map(
              (denomination: any) => ({
                label: denomination,
                value: denomination.toLowerCase(),
              })
            ),
          })),
          rawValue: data.payload.value, // Pass full religion data
        };
      }

      // other keys → normal options
      const options: Option[] =
        data?.payload?.value?.map((item: string) => ({
          label: item,
          value: item.toLowerCase(),
        })) || [];

      return { key, options };
    });
  };

  const inputKeys: string[] = [
    "marital_status",
    "height_range",
    "weight_range",
    "ethnicity",
    "genotype",
    "religion",
    "hobbies",
    "nationality",
    "interests",
    "language_spoken",
    "relationship_type",
    "age_range",
  ];

  const inputOptions = useInputOptions(inputKeys);

  const maritalOptions: Option[] =
    inputOptions.find((o) => o.key === "marital_status")?.options || [];
  const heightOptions: Option[] =
    inputOptions.find((o) => o.key === "height_range")?.options || [];
  const weightOptions: Option[] =
    inputOptions.find((o) => o.key === "weight_range")?.options || [];
  const ethnicityOptions: Option[] =
    inputOptions.find((o) => o.key === "ethnicity")?.options || [];
  const genotypeOptions: Option[] =
    inputOptions.find((o) => o.key === "genotype")?.options || [];
  const hobbiesOptions: Option[] =
    inputOptions.find((o) => o.key === "hobbies")?.options || [];
  const interestsOptions: Option[] =
    inputOptions.find((o) => o.key === "interests")?.options || [];
  const countryOptions: Option[] =
    inputOptions.find((o) => o.key === "nationality")?.options || [];
  const languagesOptions: Option[] =
    inputOptions.find((o) => o.key === "language_spoken")?.options || [];
  const ageOptions: Option[] =
    inputOptions.find((o) => o.key === "age_range")?.options || [];
  const relationshipOptions: Option[] =
    inputOptions.find((o) => o.key === "relationship_type")?.options || [];
  const nationalityRaw =
    inputOptions.find((o) => o.key === "nationality")?.rawValue || {};
  const religionOptions: Option[] =
    inputOptions.find((o) => o.key === "religion")?.options || [];

  const selectedCountry = country; // e.g., 'nigeria'

  // Find the country key in the raw object (which has capitalized names)

  const countryKey = Object.keys(nationalityRaw)?.find(
    (name) => name.toLowerCase() === selectedCountry.toLowerCase()
  );

  const stateOptions: Option[] = countryKey
    ? nationalityRaw[countryKey].states.map((stateName: string) => ({
        label: stateName,
        value: stateName.toLowerCase(),
      }))
    : [];

  // get lga options based on state
  const state = useAppSelector((state) => state.profile.state);

  const lgaOptions: Option[] =
    countryKey && state && nationalityRaw[countryKey]?.lgas?.[state]
      ? nationalityRaw[countryKey].lgas[state].map((lgaName: string) => ({
          label: lgaName,
          value: lgaName.toLowerCase(),
        }))
      : [];

  // console.log(nationalityRaw, "is raw");
  // console.log(lgaOptions, "is lga");
  // console.log(state, "is state");

  const openHobbiesPopup = () => {
    setIsEditHobbies(true);
  };

  const openInterestPopup = () => {
    setIsEditInterests(true);
  };

  const handleHobbiesUpdate = (updated: SelectOption[]) => {
    const values = updated.map((option) => option.label);
    dispatch(setHobbies(values));
  };

  const handleInterestsUpdate = (updated: SelectOption[]) => {
    const values = updated.map((option) => option.label);

    // Dispatch the updated interests values to the Redux store
    dispatch(setInterests(values));

    //  / handleEditInterests(values);
  };

  // profile photo and cover photo
  const previewSrc = useAppSelector((state) => state.profile.previewSrc);

  useEffect(() => {
    let objectUrl: string | undefined;

    if (profilePicture instanceof File) {
      objectUrl = URL.createObjectURL(profilePicture);
      dispatch(setPreviewSrc(objectUrl));
    } else if (
      typeof profilePicture === "string" &&
      profilePicture.trim() !== ""
    ) {
      dispatch(setPreviewSrc(profilePicture));
    } else if (
      typeof userProfile?.photo === "string" &&
      userProfile.photo.trim() !== ""
    ) {
      dispatch(setPreviewSrc(userProfile.photo));
    } else {
      dispatch(setPreviewSrc(undefined));
    }

    return () => {
      if (objectUrl) {
        URL.revokeObjectURL(objectUrl);
      }
    };
  }, [profilePicture, userProfile]);

  let coverPreviewSrc = "/images/cover-photo.png";

  if (coverPhoto instanceof File) {
    coverPreviewSrc = URL.createObjectURL(coverPhoto);
  } else if (userProfile?.cover_photo) {
    coverPreviewSrc = userProfile.cover_photo;
  }

  useEffect(() => {
    let objectUrl: string | null = null;

    if (coverPhoto instanceof File) {
      objectUrl = URL.createObjectURL(coverPhoto);
    }

    return () => {
      if (objectUrl) {
        URL.revokeObjectURL(objectUrl);
      }
    };
  }, [coverPhoto]);

 

  const handleEditHobbies = async (hobbies: any) => {
    try {
      setIsLoading(true);
      const userId = localStorage.getItem("userId");

      const hobbyValues = hobbies?.map((hobby: any) => hobby.label);

      const response = await axiosInstance.put(
        `/users/${userId}/hobbies-interests`,
        {
          hobbies: hobbyValues,
          interest: interests,
          language_spoken: languages?.map((item: any) => item.label),
        }
      );

      await refetchHobbiesData();
      setIsLoading(false);
    } catch (error) {
      console.error("Error updating hobbies:", error);
    }
  };

  const handleEditInterests = async (updatedInterests: string[]) => {
    try {
      setIsLoading(true);
      const userId = localStorage.getItem("userId");

      if (!userId) {
        throw new Error("UserID not provided");
      }

      const interestsValues = updatedInterests?.map(
        (interets: any) => interets?.label
      );

      const response = await axiosInstance.put(
        `/users/${userId}/hobbies-interests`,
        {
          interest: interestsValues, // Use updated interests passed to the function
          hobbies,
          language_spoken: languages?.map((item: any) => item?.label),
        }
      );

      console.log({ interestsValues });
      await refetchHobbiesData();
      setIsLoading(false);
    } catch (error) {
      console.error("Error updating interests:", error);
    }
  };

  return (
    <div className="min-h-screen mx-auto max-w-[90%] relative lg:-mt-[50px] mt-4 lg:px-24 overflow-x-hidden">
      {updatesection !== null &&
        (updatesection === "interests" || updatesection === "hobbies") && (
          <>
            <Overlay func={() => {}} />
            <div className="fixed inset-0 z-30 flex items-center justify-center">
              <MultiSelect
                options={languages}
                onSave={(items) => {
                  console.log("Saved items:", items);
                  setUpdateSection(null);
                }}
                onCancel={() => setUpdateSection(null)}
                onUnmount={(items) => {
                  console.log("Component unmounted with items:", items);
                }}
              />
            </div>
          </>
        )}

      {updatesection !== null &&
        (updatesection === "edit" || updatesection === "match") && (
          <>
            <div
              className="fixed inset-0 bg-black/20 bg-opacity-50 z-20"
              onClick={() => {
                console.log("Overlay clicked directly");
                handleCloseEditSection();
              }}
            />

            <div className="fixed inset-0 z-30 flex flex-col items-center justify-center pointer-events-none">
              <div
                className="pointer-events-auto"
                onClick={(e) => e.stopPropagation()}
              >
                <Edit
                  selectedStep={updatesection}
                  onSave={() => handleSaveSection(updatesection)}
                  onCancel={() => {
                    console.log("Cancel button clicked");
                    handleCloseEditSection();
                  }}
                  maritalOptions={maritalOptions}
                  weightOptions={weightOptions}
                  heightOptions={heightOptions}
                  genotypeOptions={genotypeOptions}
                  ethnicityOptions={ethnicityOptions}
                  religionOptions={religionOptions}
                  languagesOption={languagesOptions}
                  relationshipOptions={relationshipOptions}
                  interestsOptions={interestsOptions}
                  hobbiesOptions={hobbiesOptions}
                  ageOptions={ageOptions}
                  countryOptions={countryOptions}
                  stateOptions={stateOptions}
                  lgaOptions={lgaOptions}
                  formData={formData}
                  setFormData={setFormData}
                />
              </div>
            </div>
          </>
        )}

      {/* Hidden file inputs */}
      <input
        type="file"
        ref={profilePictureInputRef}
        onChange={(e) => handleFileChange(e, "profile")}
        accept="image/*"
        className="hidden"
      />

      <input
        type="file"
        ref={coverPhotoInputRef}
        onChange={(e) => handleFileChange(e, "cover")}
        accept="image/*"
        className="hidden"
      />
      <input
        type="file"
        ref={inputRef}
        onChange={handleGalleryFileChange}
        accept="image/*"
        className="hidden"
      />

      {/* Cover Photo with Profile */}
      <div className="relative w-full lg:h-[220px] h-[200px] bg-gray-200">
        <Image
          src={coverPreviewSrc || "/images/cover-photo.png"}
          alt="Cover"
          fill
          className="object-cover"
          priority
        />

        {/* Back Button */}
        <div className="absolute top-6 left-6 z-10">
          <Button
            variant="secondary"
            className={
              viewMode
                ? "bg-black hover:bg-black text-white rounded-md h-8 px-4 py-0 cursor-pointer"
                : "bg-[#00000099] hover:bg-[#00000099] text-white rounded-md h-8 px-4 py-0 cursor-pointer"
            }
            onClick={GoBack}
          >
            Back
          </Button>
        </div>

        {/* Update Cover Button */}
        {!viewMode && (
          <div className="absolute top-6 right-6 z-10">
            <Button
              variant="secondary"
              className="bg-[#00000099] hover:bg-[#00000099] text-white rounded-md h-8 px-4 py-0 cursor-pointer"
              onClick={onUpdateCover}
            >
              Update Cover
            </Button>
          </div>
        )}

        {/* Add to favorite Button */}
        {viewMode && (
          <div className="absolute top-6 right-6 z-10">
            <Button
              variant="secondary"
              className="bg-white hover:bg-white text-black rounded-full h-8 p-5 cursor-pointer flex items-center gap-2"
              onClick={() => setLiked(!liked)}
            >
              Add to favorite{" "}
              <HeartIcon
                className={cn(
                  "h-5 w-5 ml-1",
                  liked ? "fill-red-500 text-red-500" : "text-gray-400"
                )}
              />
            </Button>
          </div>
        )}

        {/* Profile Picture and Info */}
        <ProfilePicture
          src={previewSrc}
          alt={`${userProfile?.name || "User"}'s profile`}
          viewMode={viewMode}
          onUpload={onUploadProfilePicture}
          userInfo={{
            name: userProfile?.first_name || "",
            age: userProfile?.age || 0,
            location: userProfile?.location || "",
          }}
          onEditInfo={() => handleEditSection("name")}
        />
      </div>

      {/* Action Buttons */}
      {!viewMode && (
        <div className="flex md:flex-row items-center flex-col justify-end gap-2 md:mt-5 mt-24 md:mb-24">
          {userProfileData?.payload?.has_address_verified !== false && (
            <div title="Your address has been verified">
              <Badge
                variant="outline"
                className="flex items-center gap-1 text-[0.9rem] py-0 h-5 text-ellipsis text-nowrap border-none"
              >
                <Image
                  src={"/images/verified.svg"}
                  alt="verified"
                  width={20}
                  height={20}
                />
                <span className="text-black italic font-[200]">
                  Address Verified
                </span>
              </Badge>
            </div>
          )}

          <RequestAddressCheck />
          <Button
            variant="outline"
            className="border-none text-white hover:bg-[#EF2424] hover:text-white bg-[#EF2424] rounded-full h-9 px-4 cursor-pointer"
            onClick={() => handleEditSection("edit")}
          >
            Edit Profile
          </Button>
          <Button
            variant="outline"
            className="border-none text-white hover:bg-[#EF2424] bg-[#EF2424] hover:text-white rounded-full h-9 px-4 cursor-pointer"
            onClick={() => handleEditSection("match")}
          >
            Edit Match Setup
          </Button>
        </div>
      )}

      {/* expiry warning indicator */}
      {viewMode && pathname.includes("user/interested-in-me") && (
        <motion.div
          className="text-[#EF2424] text-[12px] font-semibold mr-12 absolute xl:right-[25%] xl:top-[240.5px] lg:right-[32%] lg:top-[240px] md:right-[28%] md:top-[200px] -right-[13%] top-[200px]"
          animate={{
            scale: [1, 1.1, 1],
            opacity: [1, 0.8, 1],
          }}
          transition={{
            duration: 1.5,
            repeat: Infinity,
            ease: "easeInOut",
          }}
        >
          6 days before interest expires
        </motion.div>
      )}

      {viewMode && pathname.includes("user/interested-in-me") && (
        <div className="text-black text-[14px] font-bold mr-12 absolute xl:left-[32%] xl:top-[240.5px] lg:left-[40%] lg:top-[280px] md:left-[34%] md:top-[220px] -right-[13%] top-[220px]">
          <AnimatedCounter value={80} suffix="% Match" />
        </div>
      )}

      {/* Nudge and Block Buttons for viewMode */}
      {viewMode && (
        <div className="flex md:flex-row flex-col justify-end items-center gap-2 md:mt-5 mt-24 md:mb-24">
          {!pathname.includes("user/mutuals") && (
            <Button className="bg-[#EF2424] hover:bg-[#EF2424]/80 text-white rounded-full h-9 px-8 cursor-pointer md:w-auto w-full text-xs">
              {pathname.includes("user/favourites")
                ? "Show interest"
                : pathname.includes("user/interested-in-me")
                  ? "Accept"
                  : "Nudge"}
            </Button>
          )}
          <Button
            variant="outline"
            className="border-[#EF2424] text-[#EF2424] hover:bg-gray-100 rounded-full h-9 px-8 cursor-pointer md:w-auto w-full"
          >
            Block
          </Button>
        </div>
      )}

      <div
        className={`mt-6 ${viewMode ? "grid md:grid-cols-2 gap-4" : ""} md:min-h-[196px] lg:mb-6`}
      >
        {/* Bio Section and Photo Gallery */}
        <div
          className={`${!viewMode ? "lg:w-[486px] md:w-3/4" : ""} h-full flex flex-col xl:justify-between md:justify-around md:gap-8 gap-y-4`}
        >
          {/* Bio Section */}
          <Card className="p-4 shadow-sm w-full">
            <div className="flex items-start">
              {updatesection !== null && updatesection === "bio" ? (
                <div className="w-full space-y-4 inline-block">
                  <Textarea
                    onChange={handleTextAreaChange}
                    value={shortBio || ""}
                    placeholder="A few words about myself"
                  ></Textarea>
                  <Button
                    className="px-4 py-2 bg-[#00000099] hover:bg-[#00000099] cursor-pointer"
                    onClick={() => handleEditBio()}
                  >
                    {isBioLoading ? (
                      <LoadingSpinner />
                    ) : (
                      <>
                        <span>
                          <Save className="h-4 w-4" />
                        </span>
                        <span>Save</span>
                      </>
                    )}
                  </Button>

                  <Button
                    className="px-4 py-2 ml-4 bg-[#EF2424] hover:bg-[#EF2424] cursor-pointer"
                    onClick={() => handleCloseEditSection()}
                  >
                    <span>
                      <XIcon className="h-4 w-4" />
                    </span>
                    <span>Cancel</span>
                  </Button>
                </div>
              ) : (
                <article className="text-gray-500 font-medium min-h-12">
                  {shortBio || "A few words about myself"}
                </article>
              )}

              {!viewMode && updatesection !== "bio" && (
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6 p-0 ml-4"
                  onClick={() => handleEditSection("bio")}
                >
                  <Pencil className="h-4 w-4" />
                </Button>
              )}
            </div>
          </Card>

          {/* Photo Gallery */}
          <Card className="px-2 py-2 shadow-sm">
            <PhotoGallery
              photos={galleryPhotos}
              maxPhotos={5}
              viewMode={false}
              onUpload={onUploadPhoto}
            />
          </Card>
        </div>

        {/* Areas Of Compatibility and Contact Details Section - Only in viewMode */}
        {viewMode && (
          <div className="flex flex-col md:flex-row gap-4 h-full bg-white shadow-sm rounded-md">
            <Card className="p-4 flex-1 shadow-none border-none">
              <h2 className="font-semibold mb-4">Areas Of Compatibility</h2>
              <div className="grid grid-cols-2 gap-y-2">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-red-500"></div>
                  <span>Height</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-red-500"></div>
                  <span>Biking</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-red-500"></div>
                  <span>Location</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-red-500"></div>
                  <span>Travel</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-red-500"></div>
                  <span>Poetry</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-red-500"></div>
                  <span>Religion</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-red-500"></div>
                  <span>Age</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-red-500"></div>
                  <span>Knitting</span>
                </div>
              </div>
            </Card>

            {pathname.includes("user/mutuals") && (
              <Card className="p-4 shadow-none border-none flex-1">
                <h2 className="font-semibold mb-4">Contact Details</h2>
                <div className="flex flex-col gap-y-2">
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-red-500"></div>
                    <span>Email: John@gmail.com</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-red-500"></div>
                    <span>Mobile number: 0907768921</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-red-500"></div>
                    <span>
                      Physical address: 3rd animasaun estate, Yaba. Lagos
                    </span>
                  </div>
                </div>
              </Card>
            )}
          </div>
        )}
      </div>
      {/* layout for Hobbies, Interests, and About Me */}
      <div className="mt-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 py-6">
        {/* Hobbies */}
        <Card className="p-4 shadow-sm h-full">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold">My Hobbies</h2>
            {!viewMode && (
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6 p-0"
                onClick={() => openHobbiesPopup()}
              >
                <Pencil className="h-4 w-4" />
              </Button>
            )}
          </div>

          <div className="grid  xl:grid-cols-4 grid-cols-3 gap-2">
            {hobbiesLoading
              ? Array.from({ length: 6 }).map((_, index) => (
                  <HobbySkeleton key={index} />
                ))
              : hobbies?.map((hobbie, index) => (
                  <HobbyComponent key={index} hobbie={hobbie} />
                ))}
          </div>
        </Card>

        {/* Interests */}
        <Card className="p-4 shadow-sm h-full">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold">My Interests</h2>
            {!viewMode && (
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6 p-0"
                onClick={() => openInterestPopup()}
              >
                <Pencil className="h-4 w-4" />
              </Button>
            )}
          </div>

          <div className="grid xl:grid-cols-4 grid-cols-3 gap-2">
            {hobbiesLoading
              ? Array.from({ length: 6 }).map((_, index) => (
                  <HobbySkeleton key={index} />
                ))
              : interests?.map((interest, index) => (
                  <InterestComponent key={index} interest={interest} />
                ))}
          </div>
        </Card>

        {/* About Me */}
        <Card className="p-4 shadow-sm h-full">
          <h2 className="font-semibold mb-4">About Me</h2>

          <div className="flex flex-col gap-y-3">
            {aboutMe && <AboutMe aboutMe={aboutMe} />}
          </div>
        </Card>

        {/* date preference section */}
        {preferredMatchesLoading
          ? Array.from({ length: 3 }).map((_, index) => (
              <div
                key={index}
                className="p-4 shadow-sm h-full border border-gray-200 rounded-md"
              >
                <div className="h-4 w-1/2 bg-gray-300 rounded mb-4 animate-pulse" />
                <LineSkeleton lines={4} />
              </div>
            ))
          : userPreferredMatches?.map((item) => (
              <Card className="p-4 shadow-sm h-full" key={item.id}>
                <h2 className="font-semibold mb-4 capitalize">
                  I'm Looking For ({item.relationship_type})
                </h2>
                <PreferredMatch item={item} />
              </Card>
            ))}
      </div>

      {isEditHobbies && (
        <MultiSelectPopup2
          options={hobbiesOptions}
          selected={hobbies?.map((hobby: any) => {
            // Check if hobby is a string or an object
            const value = typeof hobby === "string" ? hobby : hobby.label;
            return {
              label: value,
              value: value.toLowerCase(),
            };
          })}
          onClose={() => setIsEditHobbies(false)}
          onChange={handleHobbiesUpdate}
          loading={isLoading}
          onSaveApiCall={handleEditHobbies}
        />
      )}

      {isEditInterests && (
        <MultiSelectPopup2
          options={interestsOptions}
          selected={interests?.map((interest: any) => {
            // Check if interest is a string or an object
            const value =
              typeof interest === "string" ? interest : interest.label;
            return {
              label: value,
              value: value.toLowerCase(),
            };
          })}
          onClose={() => setIsEditInterests(false)}
          onChange={handleInterestsUpdate}
          loading={isLoading}
          onSaveApiCall={handleEditInterests}
        />
      )}
    </div>
  );
}
