"use client";
import { useState, useEffect, useRef, Fragment } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { MultiSelect } from "@/src/components/reusables/ui/multiselect";
import CustomSelect from "../../reusables/ui/select";
import {
  genotypeOptions,
  genderOptions,
  availableLanguages,
  relationshipOptions,
  maritalStatusOptions,
  relationshipTypeOptions,
  ageRangeOptions,
  weightRangeOptions,
  heightRangeOptions,
  nationalityOptions,
  stateOptions,
  hobbiesOptions,
  interestsOptions,
} from "@/src/utils/dummy-data/commonData";
import { usePathname } from "next/navigation";
import { EditProps, FormsData, Option } from "@/src/utils/types";
import Overlay from "../../reusables/overlay/overlay";
import RenderMultiSelectField from "../../reusables/ui/renderMultiSelect";
import { MinusIcon, PlusIcon } from "lucide-react";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/src/redux/store";
import {
  addMatchProfile,
  removeLastMatchProfile,
  updateMatchProfileAtIndex,
} from "@/src/redux/appActions";
import { MatchProfile } from "@/src/utils/types/state_types";
import { useAppSelector } from "@/src/redux/hook";
import {
  addForm,
  addNewForm,
  removeForm,
  removeNewForm,
  resetMatchupProfile,
  setMatchups,
  updateForm,
  updateNewForm,
} from "@/src/redux/matchProfileSlice";
import MultiSelectPopup from "../../reusables/MultiSelectPopup";
import LoadingSpinner from "../../reusables/ui/LoadingSpinner";
import { useGetUserBioData } from "@/src/utils/hooks/useGetBioData";
import {
  resetProfile,
  setAboutMe,
  setCountry,
  setEthnicity,
  setGender,
  setGenotype,
  setHeightRange,
  setHouseNumber,
  setInterests,
  setLandmark,
  setLanguages,
  setLGA,
  setMaritalStatus,
  setOccupation,
  setPostcode,
  setReligions,
  setState,
  setStreetName,
  setSubReligions,
  setUserHobbies,
  setUserInterests,
  setUserProfile,
  setWeightRange,
} from "@/src/redux/profileSlice";
import { useGetUserContact } from "@/src/utils/hooks/useGetContact";
import { useGetHobbiesData } from "@/src/utils/hooks/useGetHobbies";
import { useGetPrefferedMatchData } from "@/src/utils/hooks/useGetPrefferedMatches";
import { useGetUserPreferredMatches } from "@/src/utils/hooks/useGetUserPreferredMatches";
import axiosInstance from "@/lib/axios";
import { useGetUserProfile } from "@/src/utils/hooks/useGetUserProfile";

export default function Edit({
  selectedStep,
  onUnmount,
  onCancel,
  onSave,
  formData,
  setFormData,
  back,
  weightOptions,
  heightOptions,
  maritalOptions,
  genotypeOptions,
  ethnicityOptions,
  religionOptions,
  languagesOption,
  ageOptions,
  relationshipOptions,
  countryOptions,
  hobbiesOptions,
  interestsOptions,
  stateOptions,
  lgaOptions,
}: EditProps) {
  const [showMultiSelect, setShowMultiSelect] = useState(false);
  const [currentField, setCurrentField] = useState("");
  const [currentOptions, setCurrentOptions] = useState<string[]>([]);
  const editcontainerRef = useRef<HTMLDivElement>(null);
  const [activeTab, setActiveTab] = useState("bio-data");
  const [religion, setReligion] = useState<string>("");
  const [relationshipSections, setRelationshipSections] = useState([
    { id: Date.now() },
  ]);
  const [path, setPath] = useState<string>("");
  const [subReligion, setSubReligion] = useState<string>("");
  const matchProfileDetails = useSelector(
    (state: RootState) => state.counter.matchProfiles
  );
  const gender = useAppSelector((state) => state.profile.gender);

  const handleReligionChange = (value: string, subValue?: string) => {
    if (subValue) {
      // Dispatch the selected religion and sub-religion to Redux
      dispatch(setReligions(value));
      dispatch(setSubReligions(subValue));
    } else {
      // Dispatch the selected religion and clear the sub-religion
      dispatch(setReligions(value));
      dispatch(setSubReligions(""));
    }
    setHasBiodataChanged(true);
  };

  // Single handler for all input changes
  // const handleChange = (field: string, value: unknown) => {
  //   setFormData((prev) => ({
  //     ...prev,
  //     [field]: value,
  //   }));
  // };
  const dispatch = useDispatch();
  const handleChange = (field: any, value: any, index?: number | any) => {
    dispatch(updateMatchProfileAtIndex({ index, field, value }));
  };

  const handleSave = async () => {
    await handleAddMatchups();
  };

  const goBack = () => {
    if (back) {
      back();
    }

    if (onCancel) {
      console.log("calcelled");
      onCancel();
    }
  };

  const [currentProfileIndex, setCurrentProfileIndex] = useState<number>(0);
  const [isLoading, setIsLoading] = useState(false);

  const openMultiSelect = (
    field: string,
    options: string[],
    index?: number
  ) => {
    if (index) {
      setCurrentProfileIndex(index);
    }
    setCurrentField(field);
    setCurrentOptions(options);
    setShowMultiSelect(true);
  };

  const handleMultiSelection = (selectedValues: string[]) => {
    // setFormData((prev) => ({
    //   ...prev,
    //   [currentField]: selectedValues,
    // }));
    // handleChange2(
    //   currentProfileIndex,
    //   currentField as keyof MatchProfile,
    //   selectedValues
    // );
    setShowMultiSelect(false);
  };
  console.log({ relationshipOptions });

  const pathname = usePathname();
  useEffect(() => {
    setPath(pathname);
  }, [pathname]);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        editcontainerRef.current &&
        !editcontainerRef.current.contains(event.target as Node)
      ) {
        if (onCancel) {
          document.body.style.overflow = "auto";
          onCancel();
        }
      }
    }

    document.addEventListener("mousedown", handleClickOutside);

    if (editcontainerRef.current) {
      document.body.style.overflow = "hidden";
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.body.style.overflow = "auto";
      if (onUnmount) {
        onUnmount(formData);
      }
    };
  }, [onCancel, onUnmount, formData]);

  // Ensure array fields are initialized
  useEffect(() => {
    if (selectedStep === "match") {
      setFormData(
        (prev: any): FormData => ({
          ...prev,
          relationshipType: prev.relationshipType || [],
          ageRange: prev.ageRange || [],
          weightRange: prev.weightRange || "",
          heightRange: prev.heightRange || "",
          maritalStatus: prev.maritalStatus || "",
          ethnicity: prev.ethnicity || "",
          genotype: prev.genotype || "",
          hobbies: prev.hobbies || [],
          interests: prev.interests || [],
          nationality: prev.nationality || "",
          state: prev.state || "",
          religion: prev.religion || "",
        })
      );
    }
  }, [selectedStep, setFormData]);

  const addRelationshipSection = () => {
    dispatch(addMatchProfile());
  };

  const removeRelationshipSection = () => {
    dispatch(removeLastMatchProfile());
  };

  useEffect(() => {
    console.log(matchProfileDetails, "is match details");
  }, [matchProfileDetails]);

  const oppositeGender = gender === "Male" ? "Female" : "Male";
  const [errorMessage, setErrorMessage] = useState(""); // State for error message
  const [successMessage, setSuccessMessage] = useState("");

  useEffect(() => {
    const hasMessage = errorMessage || successMessage;

    if (!hasMessage) return;

    const timer = setTimeout(() => {
      setErrorMessage("");
      setSuccessMessage("");
    }, 3000);

    return () => clearTimeout(timer);
  }, [errorMessage, successMessage]);

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [hasBiodataChanged, setHasBiodataChanged] = useState(false);
  const [hasContactChanged, setHasContactChanged] = useState(false);
  const [hasHobbiesChanged, setHasHobbiesChanged] = useState(false);
  const [hasMatchesChanged, setHasMatchesChanged] = useState(false);
  const [matchupButton, setMatchupButton] = useState(false);
  const [isAddMatchup, setIsAddMatchup] = useState(false);
  const [validLGA, setValidLGA] = useState(false);

  const matchups = useAppSelector((state) => state.match.matchup);
  const newMatchups = useAppSelector((state) => state.match.newMatchup);
  console.log(newMatchups, "new matchups");

  console.log({ matchups });

  useEffect(() => {
    console.log(newMatchups, "new matchups renders");
  }, [newMatchups]);

  const maritalStatus = useAppSelector((state) => state.profile.maritalStatus);
  const heightRange = useAppSelector((state) => state.profile.heightRange);
  const weightRange = useAppSelector((state) => state.profile.weightRange);
  const ethnicity = useAppSelector((state) => state.profile.ethnicity);
  const genotype = useAppSelector((state) => state.profile.genotype);
  const occupation = useAppSelector((state) => state.profile.occupation);
  const religions = useAppSelector((state) => state.profile.religions);
  const languages = useAppSelector((state) => state.profile.languages);
  console.log(languages, "is lang");

  const userHobbies = useAppSelector((state) => state.profile.userHobbies);
  const userInterests = useAppSelector((state) => state.profile.userInterests);
  const subReligions = useSelector((state: any) => state.profile.subReligions);
  const houseNumber = useAppSelector((state) => state.profile.houseNumber);
  const streetName = useAppSelector((state) => state.profile.streetName);
  const lga = useAppSelector((state) => state.profile.lga);
  const landmark = useAppSelector((state) => state.profile.landmark);
  const postcode = useAppSelector((state) => state.profile.postcode);
  const state = useAppSelector((state) => state.profile.state);
  const country = useAppSelector((state) => state.profile.country);

  const aboutMe = useAppSelector((state) => state.profile.aboutMe);
  const userProfile = useAppSelector((state) => state.profile.userProfile);

  const handleAddMatchups = async () => {
    try {
      if (typeof window === "undefined") return;

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

      if (!userId) {
        setErrorMessage("User is not authenticated.");
        setIsSubmitting(false);
        setMatchupButton(false);
        return;
      }

      // Validation: Check for duplicate relationship types
      const relationshipTypes = matchups?.map(
        (form: any) => form.relationshipType
      );
      const duplicates = relationshipTypes.filter(
        (item, index) => relationshipTypes.indexOf(item) !== index
      );

      if (duplicates.length > 0) {
        setErrorMessage(
          "Each match must have a unique relationship type. Please remove duplicates."
        );
        setIsSubmitting(false);
        setMatchupButton(false);
        return;
      }

      setIsLoading(true);
      setErrorMessage(""); // Clear error message before API call
      setSuccessMessage(""); // Clear success message before API call

      console.log({ matchups });

      const preferredMatches = matchups.map((form: any) => {
        // Normalize relationshipType
        let relationshipTypeValue = form.relationshipType.toLowerCase();
        let relationshipTypeLabel = "";
        if (relationshipTypeValue === "marriage")
          relationshipTypeLabel = "Marriage";
        else if (relationshipTypeValue === "colleague")
          relationshipTypeLabel = "Colleague";
        else if (relationshipTypeValue === "friendship")
          relationshipTypeLabel = "Friendship";
        else relationshipTypeLabel = form.relationshipType; // fallback if new types are added

        console.log("hello here is a bug");
        console.log(relationshipTypeLabel, "is relationship type label");

        // Handle country transformation
        const nationality = (form.country || []).map((item: any) => {
          if (typeof item === "string") {
            return item; // return as-is
          }
          return "";
        });

        return {
          relationship_type: relationshipTypeLabel,
          gender:
            form.relationshipType === "Marriage"
              ? [oppositeGender]
              : form.gender,
          age_range: form.ageRange.map((item: any) => item),
          height_range: form.heightRange.map((item: any) => item),
          weight_range: form.weightRange.map((item: any) => item),
          language_spoken: form.languages.map((item: any) => item),
          marital_status: form.maritalStatus.map((item: any) => item),
          ethnicity: form.ethnicity.map((item: any) => item),
          genotype: form.genotype.map((item: any) => item),
          nationality: nationality,
          state: form.states.map((item: any) => item),
          hobbies: form.hobbies.map((item: any) => item),
          interest: form.interests.map((item: any) => item),
          religions: form.religions.map((religion: any) => ({
            religion: religion.religion,
            denomination: religion.denomination || "",
          })),
        };
      });

      // Send the data in the expected format
      const response = await axiosInstance.post(
        `/users/${userId}/preferred-matches`,
        {
          preferred_matches: preferredMatches,
        }
      );

      // Handle the response here if needed
      if (response.data && response.data.success) {
        setSuccessMessage("Matchups added successfully!");
      } else {
        setErrorMessage("Something went wrong. Please try again.");
      }

      onSave();
    } catch (error) {
      setErrorMessage("An error occurred while adding matchups.");
      console.log(error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleChange3 = (id: any, field: any, value: any) => {
    dispatch(updateNewForm({ id, field, value }));
  };

  const handleEditMatchupChange = (id: any, field: any, value: any) => {
    // console.log(field, value, "here1");
    dispatch(updateForm({ id, field, value }));
  };

  const {
    data: bioData,
    isLoading: bioDataLoading,
    error: bioDataError,
    refetch: refetchBioData,
  } = useGetUserBioData();

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

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

  const {
    data: matchesData,
    isLoading: matchesLoading,
    error: matchesError,
    refetch: refetchMatchesData,
  } = useGetUserPreferredMatches();

  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]);

  useEffect(() => {
    const payload = matchesData?.payload;
    console.log(payload, "is match payload");

    if (Array.isArray(payload) && payload.length) {
      const formattedMatchups = payload.map((item: any, index: number) => ({
        id: item.id,
        relationshipType: item.relationship_type || "",
        ageRange: item.age_range || [],
        maritalStatus: item.marital_status || [],
        heightRange: item.height_range || [],
        weightRange: item.weight_range || [],
        gender:
          Array.isArray(item.gender) && Array.isArray(item.gender[0])
            ? item.gender[0]
            : item.gender || [],
        religions: item.religions || [],
        genotype: item.genotype || [],
        ethnicity: item.ethnicity || [],
        languages: item.language_spoken || [],
        hobbies: item.hobbies || [],
        interests: item.interest || [],
        states: item.state || [],
        country:
          // map Nigerian to Nigeria, else use nationality as is
          Array.isArray(item.nationality)
            ? item.nationality.map((c: string) =>
                c === "Nigerian" ? "Nigeria" : c
              )
            : item.nationality === "Nigeria"
              ? ["nigeria"]
              : item.nationality || [],
      }));

      dispatch(setMatchups(formattedMatchups));
    } else {
    }
  }, [matchesData, dispatch]);

  useEffect(() => {
    if (bioData?.payload) {
      dispatch(setMaritalStatus(bioData.payload?.marital_status));
      dispatch(setHeightRange(bioData.payload?.height_range));
      dispatch(setWeightRange(bioData.payload?.weight_range));
      dispatch(setEthnicity(bioData.payload?.ethnicity));
      dispatch(setGenotype(bioData.payload?.genotype));
      dispatch(setOccupation(bioData.payload?.occupation));

      dispatch(setReligions(bioData.payload?.religions[0]?.religion));

      dispatch(setSubReligions(bioData.payload?.religions[0]?.denomination));
    }
  }, [bioData]);

  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));
    }
  }, [contactData]);

  useEffect(() => {
    if (
      !hobbiesData ||
      !languagesOption?.length ||
      !interestsOptions?.length ||
      !hobbiesOptions?.length
    )
      return;

    const payload = hobbiesData?.payload;

    console.log(payload?.language_spoken);
    console.log(languagesOption);

    // Match languages and return plain strings
    const matchedLanguages = languagesOption
      .filter((opt: any) => payload.language_spoken?.includes(opt.label))
      .map((opt: any) => opt.label); // Convert to plain strings

    console.log({ matchedLanguages });

    if (matchedLanguages.length) {
      dispatch(setLanguages(matchedLanguages)); // Now it's string[]
    }

    // Match interests and return plain strings
    const matchedInterests = interestsOptions
      .filter((opt: any) => payload.interest?.includes(opt.label))
      .map((opt: any) => opt.label);

    if (matchedInterests.length) {
      dispatch(setUserInterests(matchedInterests));
    }

    // Match hobbies and return plain strings
    const matchedHobbies = hobbiesOptions
      .filter((opt: any) => payload.hobbies?.includes(opt.label))
      .map((opt: any) => opt.label);

    // console.log(matchedHobbies, "is matched hobbies");

    if (matchedHobbies.length) {
      dispatch(setUserHobbies(matchedHobbies));
    }
  }, [
    hobbiesData,
    JSON.stringify(languagesOption),
    JSON.stringify(interestsOptions),
    JSON.stringify(hobbiesOptions),
    dispatch,
  ]);

  // edit matchups

  const editBiodata = async () => {
    try {
      setIsSubmitting(true);

      if (typeof window === "undefined") return;

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

      if (!userId) {
        setErrorMessage("User is not authenticated.");
        return;
      }

      const response = await axiosInstance.put(`/users/${userId}/bio-data`, {
        height_range: heightRange,
        weight_range: weightRange,
        ethnicity,
        genotype,
        marital_status: maritalStatus,
        occupation,
        religion: [
          {
            religion: religions,
            denomination: subReligions,
          },
        ],
      });

      await userProfileRefetch();
    } catch (error) {
      console.log(error);
    }
  };

  const editContact = async () => {
    try {
      setIsSubmitting(true);

      if (typeof window === "undefined") return;

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

      if (!userId) {
        setErrorMessage("User is not authenticated.");
        return;
      }

      const response = await axiosInstance.put(`/users/${userId}/contact`, {
        house_number: houseNumber,
        street_name: streetName,
        land_mark: landmark,
        lga: lga,
        postal_code: postcode,
        state: state,
        nationality: country,
      });

      await refetchContactData();
      await userProfileRefetch();
    } catch (error) {
      console.log(error);
    }
  };

  const editHobbiesInterest = async () => {
    try {
      setIsSubmitting(true);

      if (typeof window === "undefined") return;

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

      if (!userId) {
        setErrorMessage("User is not authenticated.");
        return;
      }

      const response = await axiosInstance.put(
        `/users/${userId}/hobbies-interests`,
        {
          hobbies: userHobbies.map((h: any) =>
            typeof h === "string" ? h : h.label
          ),
          interest: userInterests.map((i: any) =>
            typeof i === "string" ? i : i.label
          ),
          language_spoken: languages.map((l: any) =>
            typeof l === "string" ? l : l.label
          ),
        }
      );

      await refetchHobbiesData();
      await userProfileRefetch();
    } catch (error) {
      console.log(error);
    }
  };

  const editMatchups = async (id: number) => {
    try {
      setIsSubmitting(true);
      setMatchupButton(true);

      if (typeof window === "undefined") return;

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

      if (!userId) {
        setErrorMessage("User is not authenticated.");
        return;
      }

      const form = matchups.find((f: any) => f.id === id);

      if (!form) {
        setErrorMessage("Matchup not found.");
        return;
      }

      let relationshipTypeValue = form?.relationshipType?.toLowerCase();
      let relationshipTypeLabel = "";
      if (relationshipTypeValue === "marriage")
        relationshipTypeLabel = "Marriage";
      else if (relationshipTypeValue === "colleague")
        relationshipTypeLabel = "Colleague";
      else if (relationshipTypeValue === "friend")
        relationshipTypeLabel = "Friend";
      else relationshipTypeLabel = form.relationshipType;

      const nationality = (form.country || []).map((item: any) => {
        if (typeof item === "string") {
          return item; // return as-is
        }
        return "";
      });

      const getLabel = (item: any) =>
        typeof item === "string" ? item : item?.label || "";

      const updatedMatch = {
        relationship_type: relationshipTypeLabel,
        gender:
          form.relationshipType === "Marriage" ? [oppositeGender] : form.gender,
        age_range: form.ageRange.map(getLabel),
        height_range: form.heightRange.map(getLabel),
        weight_range: form.weightRange.map(getLabel),
        language_spoken: form.languages.map(getLabel),
        marital_status: form.maritalStatus.map(getLabel),
        ethnicity: form.ethnicity.map(getLabel),
        genotype: form.genotype.map(getLabel),
        nationality: nationality,
        state: form.states.map(getLabel),
        hobbies: form.hobbies.map(getLabel),
        interest: form.interests.map(getLabel),
        religions: (form.religions || []).map((r: any) => ({
          religion: r.religion,
          denomination: r.denomination || "",
        })),
      };

      console.log(updatedMatch, "is updated match");
      console.log(form.religions, "is updated match");

      await axiosInstance.put(
        `/users/${userId}/preferred-matches/${id}`,
        updatedMatch
      );

      setIsSubmitting(false);
      onSave();
      await refetchMatchesData();
      await userProfileRefetch();
    } catch (error) {
      console.log(error);
    } finally {
      setMatchupButton(false);
    }
  };

  useEffect(() => {
    console.log(matchups, "is form religions");
  }, [matchups]);

  const handleAddNewMatchUp = async () => {
    try {
      setIsSubmitting(true);
      setMatchupButton(true);

      if (typeof window === "undefined") return;

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

      if (!userId) {
        setErrorMessage("User is not authenticated.");
        return;
      }

      const preferredMatches = newMatchups.map((form: any) => {
        // Normalize relationshipType
        let relationshipTypeValue = form?.relationshipType.toLowerCase();
        let relationshipTypeLabel = "";
        if (relationshipTypeValue === "marriage")
          relationshipTypeLabel = "Marriage";
        else if (relationshipTypeValue === "colleague")
          relationshipTypeLabel = "Colleague";
        else if (relationshipTypeValue === "friendship")
          relationshipTypeLabel = "Friendship";
        else relationshipTypeLabel = form.relationshipType.label;

        console.log("hello here is a bug");
        console.log(relationshipTypeLabel, "is relationship type label");

        // Handle country transformation
        const nationality = form.country.map((item: any) => item);

        return {
          relationship_type: relationshipTypeLabel,
          gender:
            form.relationshipType === "Marriage"
              ? [oppositeGender]
              : form.gender,
          age_range: form.ageRange.map((item: any) => item),
          height_range: form.heightRange.map((item: any) => item),
          weight_range: form.weightRange.map((item: any) => item),
          language_spoken: form.languages.map((item: any) => item),
          marital_status: form.maritalStatus.map((item: any) => item),
          ethnicity: form.ethnicity.map((item: any) => item),
          genotype: form.genotype.map((item: any) => item),
          nationality: nationality,
          state: form.states.map((item: any) => item),
          hobbies: form.hobbies.map((item: any) => item),
          interest: form.interests.map((item: any) => item),
          religions: (form.religions || []).map((r: any) => ({
            religion: r.religion,
            denomination: r.denomination || "",
          })),
        };
      });

      // Send the data in the expected format
      const response = await axiosInstance.post(
        `/users/${userId}/preferred-matches`,
        {
          preferred_matches: preferredMatches,
        }
      );

      setIsSubmitting(false);
      onSave();
      await refetchMatchesData();
      await userProfileRefetch();
    } catch (error) {
      console.log(error);
      console.log("hello");
      setIsSubmitting(false);
    } finally {
      setMatchupButton(false);
    }
  };

  const handleEditUserProfile = async () => {
    if (hasBiodataChanged) {
      await editBiodata();
    }

    if (hasContactChanged) {
      await editContact();
    }

    if (hasHobbiesChanged) {
      await editHobbiesInterest();
    }

    setIsSubmitting(false);
    if (onSave) {
      onSave();
    }
  };

  useEffect(() => {
    const isValid = lgaOptions?.some(
      (opt: Option) => opt.value.toLowerCase() === lga.toLowerCase()
    );
    setValidLGA(isValid);
  }, [state, lga, lgaOptions]);

  return (
    <>
      <div
        ref={editcontainerRef}
        className="bg-white rounded-lg overflow-hidden shadow lg:w-[1050px] relative md:w-2xl w-sm mx-auto min-h-[400px] max-h-[600px] m-auto flex flex-col"
      >
        <div className="bg-gradient-to-r from-[#FB4F4F] via-[#DE2B2B] to-[#E46363] text-white py-8 px-6 h-[100px] flex items-center justify-center sticky top-0 z-10">
          <h1 className="text-xl font-semibold text-center">
            {selectedStep === "edit"
              ? "Edit Profile"
              : selectedStep === "match"
                ? pathname.includes("/profile-setup")
                  ? "Match Profile Setup"
                  : !path.includes("profile-setup") && isAddMatchup
                    ? "Add Matchup Profile"
                    : "Match profile edit"
                : ""}
          </h1>
        </div>

        {/* Scrollable content area */}
        <div className="px-6 sm:px-12 py-6 overflow-y-auto flex-grow">
          {/* Step Content */}
          <AnimatePresence mode="wait">
            {selectedStep === "edit" && (
              <Fragment>
                <div className="p-3 sm:p-6">
                  <h3 className="text-black font-medium mb-6 sm:mb-12 text-sm sm:text-[14px]">
                    Edit your profile
                  </h3>

                  <div className="mb-4 sm:mb-6">
                    <Tabs
                      value={activeTab}
                      onValueChange={setActiveTab}
                      className="w-full lg:w-[497px] md:w-3/4"
                    >
                      <TabsList className="bg-[#EF2424] rounded-md p-1 w-full grid grid-cols-3 place-content-center py-2 sm:py-8">
                        <TabsTrigger
                          value="bio-data"
                          className="text-white data-[state=active]:bg-white data-[state=active]:text-black rounded-md cursor-pointer !font-medium text-[10px] sm:text-[12px] h-[30px] sm:h-[38px] px-1 sm:px-2"
                        >
                          Bio-data
                        </TabsTrigger>
                        <TabsTrigger
                          value="contact"
                          className="text-white data-[state=active]:bg-white data-[state=active]:text-black rounded-md cursor-pointer !font-medium text-[10px] sm:text-[12px] px-1 sm:px-2"
                        >
                          Contact
                        </TabsTrigger>
                        <TabsTrigger
                          value="hobbies"
                          className="text-white data-[state=active]:bg-white data-[state=active]:text-black rounded-md cursor-pointer !font-medium text-[10px] sm:text-[12px] px-1 sm:px-2"
                        >
                          Hobbies
                        </TabsTrigger>
                      </TabsList>
                    </Tabs>
                  </div>

                  <div className="mt-4 sm:mt-6">
                    {activeTab === "bio-data" && (
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-6">
                        <div>
                          <CustomSelect
                            value={maritalStatus}
                            onChange={(selected) => {
                              dispatch(setMaritalStatus(selected));
                              setHasBiodataChanged(true);
                            }}
                            options={maritalOptions}
                            label="Marital Status"
                            placeholder="Please select an option"
                          />
                        </div>

                        <div>
                          <CustomSelect
                            value={heightRange}
                            onChange={(selected) => {
                              dispatch(setHeightRange(selected));
                              setHasBiodataChanged(true);
                            }}
                            options={heightOptions}
                            label="Height Range"
                            placeholder="Please select an option"
                          />
                        </div>

                        <div>
                          <CustomSelect
                            value={weightRange}
                            onChange={(selected) => {
                              dispatch(setWeightRange(selected));
                              setHasBiodataChanged(true);
                            }}
                            options={weightOptions}
                            label="Weight Range"
                            placeholder="Please select an option"
                          />
                        </div>

                        <div>
                          <CustomSelect
                            value={ethnicity}
                            onChange={(selected) => {
                              dispatch(setEthnicity(selected));
                              setHasBiodataChanged(true);
                            }}
                            options={ethnicityOptions}
                            label="Ethnicity"
                            placeholder="Please select an option"
                          />
                        </div>

                        <div>
                          <CustomSelect
                            value={genotype}
                            onChange={(selected) => {
                              dispatch(setGenotype(selected));
                              setHasBiodataChanged(true);
                            }}
                            options={genotypeOptions}
                            label="Genotype"
                            placeholder="Please select an option"
                          />
                        </div>

                        <div className="mt-1 sm:mt-2">
                          <label
                            htmlFor="occupation"
                            className="block font-[400px] text-black mb-1 text-[11px] sm:text-[12px]"
                          >
                            Occupation
                          </label>
                          <Input
                            id="occupation"
                            placeholder="Occupation"
                            onChange={(e) => {
                              dispatch(setOccupation(e.target.value));
                              setHasBiodataChanged(true);
                            }}
                            value={occupation}
                            className="w-full bg-[#F9F9F9] !text-black font-light border-none focus:outline-none focus:border-none outline-none !text-[10px]"
                          />
                        </div>

                        <div className="">
                          <CustomSelect
                            value={religions}
                            subValue={subReligions}
                            onChange={handleReligionChange}
                            options={religionOptions}
                            label="Religion"
                            placeholder="Please select an option"
                          />
                        </div>
                      </div>
                    )}

                    {activeTab === "contact" && (
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-6">
                        <div className="my-1 sm:my-2">
                          <label
                            htmlFor="House number"
                            className="block text-[11px] sm:text-[12px] text-black font-[400px] mb-1"
                          >
                            Physical Address
                          </label>
                          <Input
                            id="House number"
                            placeholder="House Number"
                            value={houseNumber}
                            onChange={(e) => {
                              dispatch(setHouseNumber(e.target.value));
                              setHasContactChanged(true);
                            }}
                            className="w-full bg-[#F9F9F9] border-none focus:outline-none focus:border-none outline-none !text-[10px]"
                          />
                        </div>

                        <div className="my-1 sm:my-2">
                          <label
                            htmlFor="street name"
                            className="block text-[11px] sm:text-[12px] mb-1 text-black font-[400px] sm:hidden"
                          >
                            Street Name
                          </label>
                          <Input
                            id="street name"
                            value={streetName}
                            onChange={(e) => {
                              dispatch(setStreetName(e.target.value));
                              setHasContactChanged(true);
                            }}
                            placeholder="Street name"
                            className="w-full bg-[#F9F9F9] border-none focus:outline-none focus:border-none outline-none !text-[10px] sm:mt-6"
                          />
                        </div>

                        <div className="my-1 sm:my-2">
                          <label
                            htmlFor="landmark"
                            className="block text-[11px] sm:text-[12px] mb-1 text-black font-[400px] sm:hidden"
                          >
                            Land Mark
                          </label>
                          <Input
                            id="landmark"
                            value={landmark}
                            onChange={(e) => {
                              dispatch(setLandmark(e.target.value));
                              setHasContactChanged(true);
                            }}
                            placeholder="Land mark"
                            className="w-full bg-[#F9F9F9] border-none focus:outline-none focus:border-none outline-none !text-[10px]"
                          />
                        </div>

                        <div className="my-1 sm:my-2">
                          <label
                            htmlFor="postal code"
                            className="block text-[11px] sm:text-[12px] mb-1 text-black font-[400px] sm:hidden"
                          >
                            Postal code
                          </label>
                          <Input
                            id="postal code"
                            placeholder="Postal code"
                            value={postcode}
                            onChange={(e) => {
                              dispatch(setPostcode(e.target.value));
                              setHasContactChanged(true);
                            }}
                            className="w-full bg-[#F9F9F9] focus:bg-[#D9D9D9] border-none focus:outline-none focus:border-none outline-none !text-[10px]"
                          />
                        </div>

                        <div className="">
                          <label
                            htmlFor="country"
                            className="block text-[11px] sm:text-[12px] mb-1 text-black font-[400px] sm:hidden"
                          >
                            Country
                          </label>

                          <CustomSelect
                            value={country}
                            onChange={(val) => {
                              dispatch(setCountry(val));
                              setHasContactChanged(true);
                            }}
                            options={countryOptions}
                            placeholder="Please select country"
                          />
                        </div>

                        <div className="">
                          <label
                            htmlFor="state"
                            className="block text-[11px] sm:text-[12px] mb-1 text-black font-[400px] sm:hidden"
                          >
                            State
                          </label>

                          <CustomSelect
                            value={state}
                            onChange={(val) => {
                              dispatch(setState(val));
                              setHasContactChanged(true);
                            }}
                            options={stateOptions}
                            placeholder="Please select state"
                          />
                        </div>

                        <div className="my-1 sm:my-2">
                          <label
                            htmlFor="lga"
                            className="block text-[11px] sm:text-[12px] mb-1 text-black font-[400px] sm:hidden"
                          >
                            LGA
                          </label>

                          <CustomSelect
                            value={lga}
                            onChange={(val) => {
                              dispatch(setLGA(val));
                              setHasContactChanged(true);
                            }}
                            options={lgaOptions}
                            placeholder="Select LGA"
                          />
                        </div>
                      </div>
                    )}

                    {activeTab === "hobbies" && (
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-6">
                        <MultiSelectPopup
                          label="Hobbies"
                          options={hobbiesOptions}
                          selected={userHobbies}
                          onChange={(val: any) => {
                            dispatch(setUserHobbies(val));
                            setHasHobbiesChanged(true);
                          }}
                        />

                        <MultiSelectPopup
                          label="Interests"
                          options={interestsOptions}
                          selected={userInterests}
                          onChange={(val: any) => {
                            dispatch(setUserInterests(val));
                            setHasHobbiesChanged(true);
                          }}
                        />

                        <MultiSelectPopup
                          label="Languages Spoken"
                          options={languagesOption}
                          selected={languages}
                          onChange={(val: any) => {
                            dispatch(setLanguages(val));
                            setHasHobbiesChanged(true);
                          }}
                        />
                      </div>
                    )}

                    {showMultiSelect && (
                      <>
                        <Overlay func={() => {}} />
                        <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-0">
                          <div className="w-full sm:w-auto max-w-full sm:max-w-md md:max-w-lg">
                            <MultiSelect
                              options={currentOptions}
                              onSave={handleMultiSelection}
                              onCancel={() => setShowMultiSelect(false)}
                              onUnmount={(selectedValues) => {
                                console.log(
                                  `${currentField} on unmount:`,
                                  selectedValues
                                );
                                handleChange(currentField, selectedValues);
                              }}
                              initialSelections={
                                formData &&
                                Array.isArray(formData[currentField])
                                  ? formData[currentField]
                                  : []
                              }
                            />
                          </div>
                        </div>
                      </>
                    )}
                  </div>
                </div>
              </Fragment>
            )}
            {selectedStep === "match" && pathname.includes("profile-setup") && (
              <motion.div
                key="match-profile"
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: 20 }}
                transition={{ duration: 0.3 }}
                className="space-y-6"
              >
                <div className="p-4 max-w-[90%] mx-auto">
                  {matchups?.map((form: any, index: any) => (
                    <div key={form.id} className="md:p-4 p-0 mb-4 ">
                      <div className="grid md:grid-cols-2 gap-4">
                        <CustomSelect
                          value={form.relationshipType}
                          onChange={(value, label) => {
                            // Use label (capitalized) instead of value
                            handleEditMatchupChange(
                              form.id,
                              "relationshipType",
                              label ?? value
                            );
                          }}
                          options={relationshipOptions}
                          label="Relationship Type"
                          placeholder="Relationship Type"
                        />

                        <div>
                          {form.relationshipType === "Marriage" ? (
                            <>
                              <label
                                htmlFor="full name"
                                className="block text-[10px] text-black mb-1 font-[400px]"
                              >
                                Gender
                              </label>
                              <Input
                                id="gender"
                                placeholder="Gender"
                                readOnly
                                disabled
                                value={oppositeGender}
                                className="w-full bg-[#D9D9D9] text-black font-bold !text-[10px] border-none focus:outline-none focus:border-none outline-none"
                              />
                            </>
                          ) : (
                            <MultiSelectPopup
                              label="Gender"
                              options={genderOptions}
                              selected={
                                Array.isArray(form.gender)
                                  ? form.gender
                                  : [form.gender].filter(Boolean)
                              }
                              onChange={(value) =>
                                handleEditMatchupChange(
                                  form.id,
                                  "gender",
                                  value
                                )
                              }
                            />
                          )}
                        </div>
                        <MultiSelectPopup
                          label="Age Range"
                          options={ageOptions}
                          selected={form.ageRange?.filter(Boolean)}
                          onChange={(value) =>
                            handleEditMatchupChange(form.id, "ageRange", value)
                          }
                        />
                        <MultiSelectPopup
                          label="Height Range"
                          options={heightOptions}
                          selected={form.heightRange}
                          onChange={(value) =>
                            handleEditMatchupChange(
                              form.id,
                              "heightRange",
                              value
                            )
                          }
                        />
                        <MultiSelectPopup
                          label="Weight Range"
                          options={weightOptions}
                          selected={form.weightRange}
                          onChange={(value) =>
                            handleEditMatchupChange(
                              form.id,
                              "weightRange",
                              value
                            )
                          }
                        />

                        <MultiSelectPopup
                          label="Marital Status"
                          options={maritalOptions}
                          selected={form.maritalStatus}
                          onChange={(value) =>
                            handleEditMatchupChange(
                              form.id,
                              "maritalStatus",
                              value
                            )
                          }
                        />

                        <MultiSelectPopup
                          label="Ethnicity"
                          options={ethnicityOptions}
                          selected={form.ethnicity}
                          onChange={(value) =>
                            handleEditMatchupChange(form.id, "ethnicity", value)
                          }
                        />

                        <MultiSelectPopup
                          label="Genotype"
                          options={genotypeOptions}
                          selected={form.genotype}
                          onChange={(value) =>
                            handleEditMatchupChange(form.id, "genotype", value)
                          }
                        />

                        <MultiSelectPopup
                          label="Country"
                          options={countryOptions}
                          selected={form.country}
                          onChange={(value) =>
                            handleEditMatchupChange(form.id, "country", value)
                          }
                        />

                        <MultiSelectPopup
                          label="State"
                          options={stateOptions}
                          selected={form.states}
                          onChange={(value) =>
                            handleEditMatchupChange(form.id, "states", value)
                          }
                        />

                        <MultiSelectPopup
                          label="Languages"
                          options={languagesOption}
                          selected={form.languages}
                          onChange={(value) =>
                            handleEditMatchupChange(form.id, "languages", value)
                          }
                        />

                        <MultiSelectPopup
                          label="Religion"
                          options={religionOptions}
                          selected={form.religions.map((r: any) => r.religion)} // Pass only religion strings
                          onChange={(
                            selectedReligions,
                            selectedSubcategories
                          ) => {
                            const finalList = selectedReligions.map(
                              (religionValue: string) => {
                                const denominations =
                                  selectedSubcategories?.[religionValue] || [];
                                return denominations.length > 0
                                  ? denominations.map((d: any) => ({
                                      religion: religionValue,
                                      denomination: d.value,
                                    }))
                                  : [
                                      {
                                        religion: religionValue,
                                        denomination: "",
                                      },
                                    ];
                              }
                            );

                            // Flatten the array
                            const flatList = finalList.flat();
                            handleEditMatchupChange(
                              form.id,
                              "religions",
                              flatList
                            );
                          }}
                        />

                        <MultiSelectPopup
                          label="Hobbies"
                          options={hobbiesOptions}
                          selected={form.hobbies}
                          onChange={(value) => {
                            handleEditMatchupChange(form.id, "hobbies", value);
                          }}
                        />

                        <MultiSelectPopup
                          label="Interests"
                          options={interestsOptions}
                          selected={form.interests}
                          onChange={(value) => {
                            handleEditMatchupChange(
                              form.id,
                              "interests",
                              value
                            );
                          }}
                        />
                      </div>

                      {/* <div className="w-full flex flex-wrap gap-y-4 mt-6 gap-x-4">
                        <Button
                          className="bg-[#4182F926] hover:bg-[#4182F926] text-[#4182F9] rounded-md cursor-pointer w-[200px]"
                          onClick={() => dispatch(addForm())}
                        >
                          <span className="mr-1">
                            <PlusIcon />
                          </span>
                          Add more Relationship
                        </Button>
                        {index !== 0 && (
                          <Button
                            className="bg-[#EF242426] hover:bg-[#EF242426] text-[#EF2424] rounded-md cursor-pointer w-[200px]"
                            onClick={() => dispatch(removeForm(form.id))}
                          >
                            <span className="mr-1">
                              <MinusIcon />
                            </span>
                            Remove Relationship
                          </Button>
                        )}
                      </div> */}
                    </div>
                  ))}
                  {successMessage && (
                    <p className="text-green-500">{successMessage}</p>
                  )}
                  {errorMessage && (
                    <p className="text-red-500">{errorMessage}</p>
                  )}
                </div>
              </motion.div>
            )}
            {selectedStep === "match" &&
              !isAddMatchup &&
              !pathname.includes("profile-setup") && (
                <motion.div
                  key="match-profile"
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: 20 }}
                  transition={{ duration: 0.3 }}
                  className="space-y-6"
                >
                  <div className="md:p-4 p-0 max-w-[90%] mx-auto">
                    {matchups.map((form: any, index: any) => (
                      <div key={form.id} className="p-4 mb-4 ">
                        <div className="grid md:grid-cols-2 gap-4">
                          <CustomSelect
                            value={form.relationshipType}
                            onChange={(value) => {
                              // Use label (capitalized) instead of value
                              handleEditMatchupChange(
                                form.id,
                                "relationshipType",
                                value
                              );
                            }}
                            options={relationshipOptions}
                            label="Relationship Type"
                            placeholder="Relationship Type"
                          />

                          <div>
                            {form.relationshipType === "Marriage" ? (
                              <>
                                <label
                                  htmlFor="full name"
                                  className="block text-[10px] text-black mb-1 font-[400px]"
                                >
                                  Gender
                                </label>
                                <Input
                                  id="gender"
                                  placeholder="Gender"
                                  readOnly
                                  disabled
                                  value={oppositeGender}
                                  className="w-full bg-[#D9D9D9] text-black font-bold !text-[10px] border-none focus:outline-none focus:border-none outline-none"
                                />
                              </>
                            ) : (
                              <MultiSelectPopup
                                label="Gender"
                                options={genderOptions}
                                selected={
                                  Array.isArray(form.gender)
                                    ? form.gender
                                    : [form.gender].filter(Boolean)
                                }
                                onChange={(value) =>
                                  handleEditMatchupChange(
                                    form.id,
                                    "gender",
                                    value
                                  )
                                }
                              />
                            )}
                          </div>
                          <MultiSelectPopup
                            label="Age Range"
                            options={ageOptions}
                            selected={form.ageRange?.filter(Boolean)}
                            onChange={(value) =>
                              handleEditMatchupChange(
                                form.id,
                                "ageRange",
                                value
                              )
                            }
                          />
                          <MultiSelectPopup
                            label="Height Range"
                            options={heightOptions}
                            selected={form.heightRange}
                            onChange={(value) =>
                              handleEditMatchupChange(
                                form.id,
                                "heightRange",
                                value
                              )
                            }
                          />
                          <MultiSelectPopup
                            label="Weight Range"
                            options={weightOptions}
                            selected={form.weightRange}
                            onChange={(value) =>
                              handleEditMatchupChange(
                                form.id,
                                "weightRange",
                                value
                              )
                            }
                          />

                          <MultiSelectPopup
                            label="Marital Status"
                            options={maritalOptions}
                            selected={form.maritalStatus}
                            onChange={(value) =>
                              handleEditMatchupChange(
                                form.id,
                                "maritalStatus",
                                value
                              )
                            }
                          />

                          <MultiSelectPopup
                            label="Ethnicity"
                            options={ethnicityOptions}
                            selected={form.ethnicity}
                            onChange={(value) =>
                              handleEditMatchupChange(
                                form.id,
                                "ethnicity",
                                value
                              )
                            }
                          />

                          <MultiSelectPopup
                            label="Genotype"
                            options={genotypeOptions}
                            selected={form.genotype}
                            onChange={(value) =>
                              handleEditMatchupChange(
                                form.id,
                                "genotype",
                                value
                              )
                            }
                          />

                          <MultiSelectPopup
                            label="Country"
                            options={countryOptions}
                            selected={form.country}
                            onChange={(value) =>
                              handleEditMatchupChange(form.id, "country", value)
                            }
                          />

                          <MultiSelectPopup
                            label="State"
                            options={stateOptions}
                            selected={form.states}
                            onChange={(value) =>
                              handleEditMatchupChange(form.id, "states", value)
                            }
                          />

                          <MultiSelectPopup
                            label="Languages"
                            options={languagesOption}
                            selected={form.languages}
                            onChange={(value) =>
                              handleEditMatchupChange(
                                form.id,
                                "languages",
                                value
                              )
                            }
                          />

                          <MultiSelectPopup
                            label="Religion"
                            options={religionOptions}
                            selected={form.religions.map(
                              (r: any) => r.religion
                            )} // Pass only religion strings
                            onChange={(
                              selectedReligions,
                              selectedSubcategories
                            ) => {
                              const finalList = selectedReligions.map(
                                (religionValue: string) => {
                                  const denominations =
                                    selectedSubcategories?.[religionValue] ||
                                    [];
                                  return denominations.length > 0
                                    ? denominations.map((d: any) => ({
                                        religion: religionValue,
                                        denomination: d.value,
                                      }))
                                    : [
                                        {
                                          religion: religionValue,
                                          denomination: "",
                                        },
                                      ];
                                }
                              );

                              // Flatten the array
                              const flatList = finalList.flat();
                              console.log(flatList, "is flatlist");
                              handleEditMatchupChange(
                                form.id,
                                "religions",
                                flatList
                              );
                            }}
                          />

                          <MultiSelectPopup
                            label="Hobbies"
                            options={hobbiesOptions}
                            selected={form.hobbies}
                            onChange={(value) => {
                              handleEditMatchupChange(
                                form.id,
                                "hobbies",
                                value
                              );
                            }}
                          />

                          <MultiSelectPopup
                            label="Interests"
                            options={interestsOptions}
                            selected={form.interests}
                            onChange={(value) => {
                              handleEditMatchupChange(
                                form.id,
                                "interests",
                                value
                              );
                            }}
                          />
                        </div>
                        <Button
                          onClick={() => editMatchups(form.id)}
                          disabled={isSubmitting}
                          className="bg-[#EF2424] hover:bg-[#EF2424]/85 px-8 py-4 mt-5 cursor-pointer"
                        >
                          {isSubmitting ? <LoadingSpinner /> : "Save"}
                        </Button>
                      </div>
                    ))}

                    {/* <Button
                        className="bg-[#EF2424] hover:bg-[#EF2424]/85 text-white rounded-md cursor-pointer"
                        onClick={() => {
                          setMatchupButton(false);
                          setIsAddMatchup(true);
                        }}
                      >
                        Add more Relationship
                      </Button> */}

                    {successMessage && (
                      <p className="text-green-500">{successMessage}</p>
                    )}
                    {errorMessage && (
                      <p className="text-red-500">{errorMessage}</p>
                    )}
                  </div>
                </motion.div>
              )}
            {isAddMatchup && (
              <motion.div
                key="match-profile"
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: 20 }}
                transition={{ duration: 0.3 }}
                className="space-y-6"
              >
                <div className="p-4 max-w-[90%] mx-auto">
                  {newMatchups.map((form: any, index: any) => (
                    <div key={form.id} className="p-4 mb-4 ">
                      <div className="grid grid-cols-2 gap-4">
                        <CustomSelect
                          value={form.relationshipType}
                          onChange={(value, label) => {
                            // Use label (capitalized) instead of value
                            handleChange3(
                              form.id,
                              "relationshipType",
                              label ?? value
                            );
                          }}
                          options={relationshipOptions}
                          label="Relationship Type"
                          placeholder="Relationship Type"
                        />

                        <div>
                          {form.relationshipType === "Marriage" ? (
                            <>
                              <label
                                htmlFor="full name"
                                className="block text-[10px] text-black mb-1 font-[400px]"
                              >
                                Gender
                              </label>
                              <Input
                                id="gender"
                                placeholder="Gender"
                                readOnly
                                disabled
                                value={oppositeGender}
                                className="w-full bg-[#D9D9D9] text-black font-bold !text-[10px] border-none focus:outline-none focus:border-none outline-none"
                              />
                            </>
                          ) : (
                            <MultiSelectPopup
                              label="Gender"
                              options={genderOptions}
                              selected={
                                Array.isArray(form.gender)
                                  ? form.gender
                                  : [form.gender].filter(Boolean)
                              }
                              onChange={(value) =>
                                handleChange3(form.id, "gender", value)
                              }
                            />
                          )}
                        </div>
                        <MultiSelectPopup
                          label="Age Range"
                          options={ageOptions}
                          selected={form.ageRange?.filter(Boolean)}
                          onChange={(value) =>
                            handleChange3(form.id, "ageRange", value)
                          }
                        />
                        <MultiSelectPopup
                          label="Height Range"
                          options={heightOptions}
                          selected={form.heightRange}
                          onChange={(value) =>
                            handleChange3(form.id, "heightRange", value)
                          }
                        />
                        <MultiSelectPopup
                          label="Weight Range"
                          options={weightOptions}
                          selected={form.weightRange}
                          onChange={(value) =>
                            handleChange3(form.id, "weightRange", value)
                          }
                        />

                        <MultiSelectPopup
                          label="Marital Status"
                          options={maritalOptions}
                          selected={form.maritalStatus}
                          onChange={(value) =>
                            handleChange3(form.id, "maritalStatus", value)
                          }
                        />

                        <MultiSelectPopup
                          label="Ethnicity"
                          options={ethnicityOptions}
                          selected={form.ethnicity}
                          onChange={(value) =>
                            handleChange3(form.id, "ethnicity", value)
                          }
                        />

                        <MultiSelectPopup
                          label="Genotype"
                          options={genotypeOptions}
                          selected={form.genotype}
                          onChange={(value) =>
                            handleChange3(form.id, "genotype", value)
                          }
                        />

                        <MultiSelectPopup
                          label="Country"
                          options={countryOptions}
                          selected={form.country}
                          onChange={(value) =>
                            handleChange3(form.id, "country", value)
                          }
                        />

                        <MultiSelectPopup
                          label="State"
                          options={stateOptions}
                          selected={form.states}
                          onChange={(value) =>
                            handleChange3(form.id, "states", value)
                          }
                        />

                        <MultiSelectPopup
                          label="Languages"
                          options={languagesOption}
                          selected={form.languages}
                          onChange={(value) =>
                            handleChange3(form.id, "languages", value)
                          }
                        />

                        <MultiSelectPopup
                          label="Religion"
                          options={religionOptions}
                          // Pass selected as string array of religion values, normalized to lowercase
                          selected={form.religions.map((r: any) =>
                            r.religion.toLowerCase()
                          )}
                          onChange={(selectedValues, selectedSubcategories) => {
                            selectedValues.forEach((selectedReligion) => {
                              const denominationList: any =
                                selectedSubcategories[selectedReligion] || [];
                              if (denominationList.length > 0) {
                                denominationList.forEach(
                                  (denomination: any) => {
                                    handleChange3(form.id, "religions", {
                                      religion: selectedReligion,
                                      denomination:
                                        denomination.value.toLowerCase(),
                                    });
                                  }
                                );
                              } else {
                                handleChange3(form.id, "religions", {
                                  religion: selectedReligion,
                                  denomination: "",
                                });
                              }
                            });
                          }}
                        />
                      </div>

                      {/* <div className="w-full flex flex-wrap gap-y-4 mt-6 gap-x-4">
                          <Button
                            className="bg-[#4182F926] hover:bg-[#4182F926] text-[#4182F9] rounded-md cursor-pointer w-[200px]"
                            onClick={() => dispatch(addNewForm())}
                          >
                            <span className="mr-1">
                              <PlusIcon />
                            </span>
                            Add more Relationship
                          </Button>
                          {index !== 0 && (
                            <Button
                              className="bg-[#EF242426] hover:bg-[#EF242426] text-[#EF2424] rounded-md cursor-pointer w-[200px]"
                              onClick={() => dispatch(removeNewForm(form.id))}
                            >
                              <span className="mr-1">
                                <MinusIcon />
                              </span>
                              Remove Relationship
                            </Button>
                          )}
                        </div> */}
                    </div>
                  ))}
                  {successMessage && (
                    <p className="text-green-500">{successMessage}</p>
                  )}
                  {errorMessage && (
                    <p className="text-red-500">{errorMessage}</p>
                  )}
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {showMultiSelect && (
            <>
              <Overlay func={() => {}} />
              <div className="fixed inset-0 z-50 flex items-center justify-center">
                <MultiSelect
                  options={currentOptions}
                  onSave={handleMultiSelection}
                  onCancel={() => setShowMultiSelect(false)}
                  onUnmount={(selectedValues) => {
                    console.log(`${currentField} on unmount:`, selectedValues);
                    handleChange(currentField, selectedValues);
                  }}
                  initialSelections={
                    Array.isArray(formData[currentField])
                      ? formData[currentField]
                      : []
                  }
                />
              </div>
            </>
          )}

          {/* Footer with Save button */}
          {!path.includes("profile-setup") && selectedStep === "edit" && (
            <div
              className={`flex my-8 ${path === "/user/profile" ? "justify-start pl-8" : "justify-center"}`}
            >
              <Button
                onClick={() => handleEditUserProfile()}
                disabled={isSubmitting}
                className="bg-[#EF2424] hover:bg-[#EF2424]/85 px-6 py-4 cursor-pointer"
              >
                {isSubmitting ? <LoadingSpinner /> : "Save"}
              </Button>
            </div>
          )}

          {!path.includes("profile-setup") && isAddMatchup && (
            <div
              className={`flex ${selectedStep === "match" && path === "/user/profile" ? "justify-start pl-8" : "justify-center"}`}
            >
              <Button
                onClick={() => handleAddNewMatchUp()}
                disabled={isSubmitting}
                className="bg-[#EF2424] hover:bg-[#EF2424]/85 px-6 py-4 cursor-pointer"
              >
                {isSubmitting ? <LoadingSpinner /> : "Save now"}
              </Button>
            </div>
          )}

          {path.includes("profile-setup") && (
            <div className="flex space-x-4 my-5 justify-center items-center">
              <Button
                onClick={(e) => {
                  e.stopPropagation();
                  goBack();
                }}
                variant="outline"
                className="bg-[#FB4F4F] hover:bg-[#FB4F4F]/85 cursor-pointer hover:text-white text-white"
              >
                Back
              </Button>
              <Button
                onClick={handleSave}
                disabled={isLoading}
                className="bg-[#FB4F4F] hover:bg-[#FB4F4F]/85 cursor-pointer text-white"
              >
                {isLoading ? <LoadingSpinner /> : "Finish"}
              </Button>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
