"use client";
import { useEffect, useRef, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { UserCircle2, Plus } from "lucide-react";
import CustomSelect from "@/src/components/reusables/ui/select";
import Overlay from "@/src/components/reusables/overlay/overlay";
import Edit from "@/src/components/user/profilepage/edit";
import { useRouter } from "next/navigation";
import RenderMultiSelectField from "@/src/components/reusables/ui/renderMultiSelect";
import { MultiSelect } from "@/src/components/reusables/ui/multiselect";
import {
  hobbiesOptions,
  interestsOptions,
  countriesOptions,
  availableLanguages,
} from "@/src/utils/dummy-data/commonData";
import type { FormsData, Option } from "@/src/utils/types";
import { useDispatch, useSelector } from "react-redux";
import {
  updatePersonalInfo,
  updateContactInfo,
  updateBioDataInfo,
  updateHobbiesAndInterests,
} from "@/src/redux/appActions";
import { RootState } from "@/src/redux/store";
import { useAppDispatch, useAppSelector } from "@/src/redux/hook";
import {
  resetProfile,
  setCountry,
  setDateOfBirth,
  setEthnicity,
  setFullName,
  setGender,
  setGenotype,
  setHeightRange,
  setHobbies,
  setHouseNumber,
  setInterests,
  setLandmark,
  setLanguages,
  setLGA,
  setMaritalStatus,
  setOccupation,
  setPhoneNumber,
  setPostcode,
  setProfilePicture,
  setReligions,
  setState,
  setStreetName,
  setSubReligions,
  setWeightRange,
} from "@/src/redux/profileSlice";
import { useGetInputData } from "@/src/utils/hooks/useGetInputData";
import { toast } from "react-toastify";
import LoadingSpinner from "@/src/components/reusables/ui/LoadingSpinner";
import axiosInstance from "@/lib/axios";
import {
  setIsBiodataSetup,
  setIsContactSetup,
  setIsHobbiesSetup,
  setIsPersonalSetup,
} from "@/src/redux/authSlice";
import AuthGuard from "@/src/components/reusables/auth";
import { useInputOptions } from "@/src/utils/functions";
import { resetMatchupProfile } from "@/src/redux/matchProfileSlice";

export default function Page() {
  const [currentStep, setCurrentStep] = useState(1);
  const [verify, setVerify] = useState(false);
  const [finish, setFinish] = useState<boolean>(false);
  const [showMultiSelect, setShowMultiSelect] = useState(false);
  const [currentOptions, setCurrentOptions] = useState<string[]>([]);
  const [currentField, setCurrentField] = useState("");
  const [formData, setFormData] = useState<FormData>();
  const [religion, setReligion] = useState<string>("");
  const [subReligion, setSubReligion] = useState<string>("");
  const [isLoading, setIsLoading] = useState(false);
  const [photo, setPhoto] = useState<string | File | any>("");

  const dispatch = useAppDispatch();
  const setupDetails = useSelector(
    (state: RootState) => state.counter.profileSetup
  );

  const isBiodataSetup = useAppSelector((state) => state.auth.isBioDataSetup);
  const isPersonalSetup = useAppSelector((state) => state.auth.isPersonalSetup);
  const isContactSetup = useAppSelector((state) => state.auth.isContactSetup);
  const isHobbiesSetup = useAppSelector((state) => state.auth.isHobbiesSetup);

  useEffect(() => {
    if (!isPersonalSetup) {
      setCurrentStep(1);
    } else if (
      isPersonalSetup &&
      !isBiodataSetup &&
      !isContactSetup &&
      !isHobbiesSetup
    ) {
      setCurrentStep(2);
    } else if (
      isPersonalSetup &&
      isBiodataSetup &&
      !isContactSetup &&
      !isHobbiesSetup
    ) {
      setCurrentStep(3);
    } else if (
      isPersonalSetup &&
      isBiodataSetup &&
      isContactSetup &&
      !isHobbiesSetup
    ) {
      setCurrentStep(4);
    } else {
      setCurrentStep(1); // fallback
    }
  }, [isBiodataSetup, isPersonalSetup, isContactSetup, isHobbiesSetup]);

  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(""));
    }
    setErrors((prev) => ({ ...prev, religions: "" }));
  };

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

  const handleMultiSelection = (selectedValues: string[]) => {
    handleChange(currentField, selectedValues);

    // Dispatch to Redux only when hobbies field is updated

    if (currentField === "hobbies") {
      dispatch(setHobbies(selectedValues));

      if (selectedValues.length > 0) {
        setErrors((prev) => ({ ...prev, hobbies: "" }));
      }
    }

    if (currentField === "interests") {
      dispatch(setInterests(selectedValues));

      if (selectedValues.length > 0) {
        setErrors((prev) => ({ ...prev, interests: "" }));
      }
    }

    if (currentField === "languages") {
      dispatch(setLanguages(selectedValues));

      if (selectedValues.length > 0) {
        setErrors((prev) => ({ ...prev, languages: "" }));
      }
    }

    setShowMultiSelect(false);
  };

  const goToPreviousStep = () => {
    if (verify) {
      setVerify(false);
    }

    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleNext = async () => {
    if (currentStep == 1) {
      if (currentStep === 1) {
        console.log({ currentStep });
        setCurrentStep(currentStep + 1);
      }
    }

    if (currentStep === 2) {
      const newErrors = {
        ...errors,
        maritalStatus: maritalStatus ? "" : "Marital status is required",
        heightRange: heightRange ? "" : "Height range is required",
        weightRange: weightRange ? "" : "Weight range is required",
        ethnicity: ethnicity ? "" : "Ethnicity is required",
        genotype: genotype ? "" : "Genotype is required",
        occupation: occupation.trim() ? "" : "Occupation is required",
        religions: religions.trim() ? "" : "Religion is required",
        houseNumber: "",
        streetName: "",
        lga: "",
        landmark: "",
        postcode: "",
        state: "",
        country: "",
        hobbies: "",
        interests: "",
        languages: "",
      };

      setErrors(newErrors);

      const hasError = Object.values(newErrors).some((val) => val !== "");
      if (hasError) return;

      await handleBioDataSubmit();
      setCurrentStep(currentStep + 1);
    }

    if (currentStep === 3) {
      const newErrors = {
        ...errors,
        houseNumber: houseNumber.trim() ? "" : "House number is required",
        streetName: streetName.trim() ? "" : "Street name is required",
        lga: "",
        landmark: landmark.trim() ? "" : "Landmark is required",
        postcode: postcode.trim() ? "" : "Postal code is required",
        state: state.trim() ? "" : "State is required",
        country: country.trim() ? "" : "Country is required",
        hobbies: "",
        interests: "",
        languages: "",
      };

      setErrors(newErrors);

      const hasError = Object.values(newErrors).some((val) => val !== "");
      if (hasError) return;

      // API call or continue
      await handleContactSubmit();
      setCurrentStep(currentStep + 1);
    }

    if (currentStep === 4) {
      const newErrors = {
        ...errors,
        hobbies:
          setupDetails["hobbies&interests"].hobbies?.length > 0
            ? ""
            : "Select Hobbies",
        interests:
          setupDetails["hobbies&interests"].interests?.length > 0
            ? ""
            : "Select Interests",
        languages:
          setupDetails["hobbies&interests"].languages?.length > 0
            ? ""
            : "Select a Language",
      };

      setErrors(newErrors);

      const hasError = Object.values(newErrors).some((val) => val !== "");
      if (hasError) return;

      await handleHobbiesAndInterestSubmit();
      setFinish(true);
    }
  };

  const router = useRouter();
  const savematchProfileValues = () => {
    dispatch(setIsBiodataSetup(true));
    dispatch(setIsPersonalSetup(true));
    dispatch(setIsContactSetup(true));
    dispatch(setIsHobbiesSetup(true));
    setFinish(false);
    router.push("/user/dashboard");
  };

  const handleBack = () => {
    setCurrentStep((prev) => prev - 0);
  };

  const handleChange = (field: string, value: unknown) => {
    switch (currentStep) {
      case 1:
        dispatch(updatePersonalInfo({ [field]: value }));
        break;
      case 2:
        dispatch(updateBioDataInfo({ [field]: value }));
        break;
      case 3:
        dispatch(updateContactInfo({ [field]: value }));
        break;
      case 4:
        dispatch(updateHobbiesAndInterests({ [field]: value }));
        break;
      default:
        break;
    }
  };

  useEffect(() => {
    console.log(subReligion);
    console.log(setupDetails, "is setup details");
  }, [subReligion, setupDetails]);

  useEffect(() => {
      resetMatchupProfile();
      resetProfile();
    }, [])

  // profile Image
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const email = useAppSelector((state) => state.auth.email);
  const phoneNumber = useAppSelector((state) => state.profile.phoneNumber);
  const fullName = useAppSelector((state) => state.profile.fullName);
  const dateOfBirth = useAppSelector((state) => state.profile.dateOfBirth);
  const gender = useAppSelector((state) => state.profile.gender);
  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 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 hobbies = useAppSelector((state) => state.profile.hobbies);
  const interests = useAppSelector((state) => state.profile.interests);
  const languages = useAppSelector((state) => state.profile.languages);
  const subReligions = useSelector((state: any) => state.profile.subReligions);
  const profilePicture = useAppSelector(
    (state) => state.profile.profilePicture
  );

  console.log({ subReligions });

  const [errors, setErrors] = useState({
    profilePicture: "",
    phoneNumber: "",
    maritalStatus: "",
    heightRange: "",
    weightRange: "",
    ethnicity: "",
    religions: "",
    genotype: "",
    occupation: "",
    houseNumber: "",
    streetName: "",
    landmark: "",
    postcode: "",
    state: "",
    country: "",
    hobbies: "",
    interests: "",
    languages: "",
  });

  const handleImageChange = (e: any) => {
    const file = e.target.files?.[0];
    if (file) {
      setPhoto(file);
      console.log({ file });
    }
  };

  // handleverify
  const handleVerification = async () => {
    // Clear any previous error
    setErrors((prev) => ({ ...prev, phoneNumber: "" }));

    // Trimmed phone number for validation
    const trimmedPhone = phoneNumber.trim();

    // Validate phone number before API call
    if (!trimmedPhone) {
      setErrors((prev) => ({
        ...prev,
        phoneNumber: "Phone number is required.",
      }));
      toast.error("Please enter your phone number.");
      return;
    }

    setIsLoading(true);
    try {
      if (typeof window === "undefined") return;

      const userId = localStorage.getItem("userId"); // Get userId from localStorage

      if (!userId) {
        toast.error("Missing user ID.");
        setIsLoading(false);
        return;
      }

      const formData02 = new FormData();

      // Handle profile picture (store the File object in Redux)
      if (photo instanceof File) {
        formData02.append("photo", photo); // Append as a file
      } else {
        setIsLoading(false);
        toast.error("Invalid profile picture.");
        return;
      }

      // Append phone number
      formData02.append("phone_number", trimmedPhone);

      // API call
      const response = await axiosInstance.post(
        `/users/${userId}/personal-profile`,
        formData02
      );

      toast.success("Verification successful!");

      // Set data to Redux
      dispatch(
        setFullName(
          response.data.payload.first_name +
            " " +
            response.data.payload.middle_name +
            " " +
            response.data.payload.last_name
        )
      );

      dispatch(setGender(response.data.payload.gender));

      const date = new Date(response.data.payload.date_of_birth);
      const options: any = { year: "numeric", month: "long", day: "numeric" };
      const dateInWords = date.toLocaleDateString("en-US", options);
      dispatch(setDateOfBirth(dateInWords));

      setVerify(true);
      setIsLoading(false);
    } catch (error: any) {
      setVerify(true);
      setIsLoading(false);
      toast.error(error.response?.data.message || "Something went wrong.");
    }
  };

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

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

      if (!userId) {
        return;
      }

      setIsLoading(true);

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

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

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

      if (!userId) {
        return;
      }

      setIsLoading(true);

      const response = await axiosInstance.post(`/users/${userId}/contact`, {
        house_number: houseNumber,
        street_name: streetName,
        land_mark: landmark,
        lga: lga,
        postal_code: postcode,
        state: state,
        nationality: country,
      });
    } catch (error) {
      console.log(error);
    } finally {
      setIsLoading(false);
    }
  };

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

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

      if (!userId) {
        return;
      }

      setIsLoading(true);

      const response = await axiosInstance.post(
        `/users/${userId}/hobbies-interests`,
        {
          hobbies: hobbies,
          interest: interests,
          language_spoken: languages,
        }
      );
    } catch (error) {
      console.log(error);
    } finally {
      setIsLoading(false);
    }
  };

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

  // Call the utility hook to get options
  const inputOptions = useInputOptions(inputKeys);

  // Extract options for each key using destructuring
  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(),
      }))
    : [];

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

  // useEffect(() => {
  //   const isValid = lgaOptions.some((opt) => opt.value === lga);

  //   if (!isValid) {
  //     setErrors((prev) => ({
  //       ...prev,
  //     }));
  //   } else {
  //     setErrors((prev) => ({ ...prev}));
  //   }
  // }, [state]);

  return (
    <AuthGuard>
      <div className="min-h-screen bg-gray-100">
        {/* Main Content */}
        <div className="lg:max-w-[950px] max-w-2xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          {!finish && (
            <div className="bg-white rounded-lg overflow-hidden shadow">
              {/* Page Header */}
              <div className="bg-gradient-to-r from-[#FB4F4F] via-[#DE2B2B] to-[#E46363] text-white py-4 px-6 md:h-[70px]">
                <h1 className="text-xl font-semibold text-center">
                  {currentStep === 2
                    ? "Match Profile Setup"
                    : "User Profile Setup"}
                </h1>
              </div>

              {/* Page Content */}
              <div className="px-6 sm:px-12 py-6">
                {currentStep === 1 && (
                  <p className="text-black mb-6 font-medium text-[14px]">
                    Complete the below process to setup your profile
                  </p>
                )}

                {/* Step Indicator */}
                <div className="mb-8">
                  {/* Desktop/Tablet View - Full Stepper */}
                  <div className="hidden md:flex items-center justify-between">
                    <div className="flex flex-col items-center">
                      <motion.div
                        className={`w-8 h-8 rounded-full flex items-center justify-center text-white text-[12px] z-10  ${currentStep >= 1 ? "bg-[#FB4F4F]" : "bg-[#8C8C8C]"}`}
                        animate={{
                          backgroundColor:
                            currentStep >= 1 ? "#FB4F4F" : "#8C8C8C",
                          scale: currentStep === 1 ? [1, 1.1, 1] : 1,
                        }}
                        transition={{ duration: 0.3 }}
                      >
                        1
                      </motion.div>
                      <span className="text-[10px] mt-2 font-medium">
                        Personal Information
                      </span>
                    </div>

                    <div
                      className={`flex-1 h-[7px] -mx-2 sm:-mx-10 mb-6 ${currentStep > 1 ? "bg-[#FB4F4F]" : "bg-[#D9D9D9]"}`}
                    ></div>

                    <div className="flex flex-col items-center">
                      <motion.div
                        className={`w-8 h-8 rounded-full flex items-center justify-center text-white text-[12px] z-10 ${currentStep >= 2 ? "bg-[#FB4F4F]" : "bg-[#8C8C8C]"}`}
                        animate={{
                          backgroundColor:
                            currentStep >= 2 ? "#FB4F4F" : "#8C8C8C",
                          scale: currentStep === 2 ? [1, 1.1, 1] : 1,
                        }}
                        transition={{ duration: 0.3 }}
                      >
                        2
                      </motion.div>
                      <span className="text-[10px] mt-2 font-medium">
                        Bio-data Information
                      </span>
                    </div>

                    <div
                      className={`flex-1 h-[7px] -mx-2 sm:-mx-10 mb-6 ${currentStep > 2 ? "bg-[#FB4F4F]" : "bg-[#D9D9D9]"}`}
                    ></div>

                    <div className="flex flex-col items-center">
                      <motion.div
                        className={`w-8 h-8 rounded-full flex items-center justify-center text-white text-[12px] z-10  ${currentStep >= 3 ? "bg-[#FB4F4F]" : "bg-[#8C8C8C]"}`}
                        animate={{
                          backgroundColor:
                            currentStep >= 3 ? "#FB4F4F" : "#8C8C8C",
                          scale: currentStep === 3 ? [1, 1.1, 1] : 1,
                        }}
                        transition={{ duration: 0.3 }}
                      >
                        3
                      </motion.div>
                      <span className="text-[10px] mt-2 font-medium">
                        Contact Information
                      </span>
                    </div>

                    <div
                      className={`flex-1 h-[7px] -mx-2 sm:-mx-10 mb-6 ${currentStep > 3 ? "bg-[#FB4F4F]" : "bg-[#D9D9D9]"}`}
                    ></div>

                    <div className="flex flex-col items-center">
                      <motion.div
                        className={`w-8 h-8 rounded-full flex items-center justify-center text-white text-[12px] z-10 ${currentStep >= 4 ? "bg-[#FB4F4F]" : "bg-[#8C8C8C]"}`}
                        animate={{
                          backgroundColor:
                            currentStep >= 4 ? "#FB4F4F" : "#8C8C8C",
                          scale: currentStep === 4 ? [1, 1.1, 1] : 1,
                        }}
                        transition={{ duration: 0.3 }}
                      >
                        4
                      </motion.div>
                      <span className="text-[10px] mt-2 font-medium">
                        Hobbies & Interests
                      </span>
                    </div>
                  </div>

                  {/* Mobile View - Single Current Step */}
                  <div className="md:hidden flex flex-col items-center">
                    <motion.div
                      className="w-12 h-12 rounded-full flex items-center justify-center text-white text-lg bg-[#FB4F4F]"
                      animate={{
                        scale: [1, 1.1, 1],
                      }}
                      transition={{ duration: 0.3 }}
                    >
                      {currentStep}
                    </motion.div>
                    <span className="text-sm mt-3 font-medium text-center">
                      {currentStep === 1 && "Personal Information"}
                      {currentStep === 2 && "Bio-data Information"}
                      {currentStep === 3 && "Contact Information"}
                      {currentStep === 4 && "Hobbies & Interests"}
                    </span>
                    <div className="mt-2 text-xs text-gray-500">
                      Step {currentStep} of 4
                    </div>
                  </div>
                </div>

                {/* Step Content */}
                <AnimatePresence mode="wait">
                  {currentStep === 1 && (
                    <motion.div
                      key="step1"
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      exit={{ opacity: 0, x: 20 }}
                      transition={{ duration: 0.3 }}
                      className="space-y-12"
                    >
                      <div className="flex flex-col md:flex-row md:gap-x-20 gap-y-8">
                        <div className="flex items-start space-x-8">
                          <div className="relative">
                            <div
                              className="w-24 h-24 rounded-full bg-gray-100 border flex items-center justify-center overflow-hidden cursor-pointer"
                              onClick={() => fileInputRef.current?.click()}
                            >
                              {photo ? (
                                // Check if photo is a File object
                                photo instanceof File ? (
                                  <img
                                    src={URL.createObjectURL(photo)}
                                    alt="Profile"
                                    className="w-full h-full object-cover"
                                  />
                                ) : (
                                  // If it's a URL (string), just display the image
                                  <img
                                    src={photo}
                                    alt="Profile"
                                    className="w-full h-full object-cover"
                                  />
                                )
                              ) : (
                                <UserCircle2 className="w-20 h-20 text-gray-400" />
                              )}
                            </div>
                            <div
                              className="absolute bottom-0 right-0 bg-blue-500 rounded-full p-1 border-2 border-white cursor-pointer"
                              onClick={() => fileInputRef.current?.click()}
                            >
                              <Plus className="w-4 h-4 text-white" />
                            </div>
                            <input
                              type="file"
                              accept="image/*"
                              ref={fileInputRef}
                              onChange={handleImageChange}
                              className="hidden"
                            />
                          </div>

                          <div className="flex-1 font-semibold text-[12px] font-poppins">
                            <h3 className="text-base font-medium text-[#000000]">
                              Add profile Picture
                            </h3>
                            <p className="text-sm text-black font-light">
                              {email}
                            </p>

                            {/* Error for profile photo */}
                            {errors.profilePicture && (
                              <p className="text-red-500 text-xs mt-1">
                                {errors.profilePicture}
                              </p>
                            )}
                          </div>
                        </div>

                        <div className="md:flex-1">
                          <label
                            htmlFor="mobile"
                            className="block text-black mb-1 text-[12px] font-[400px]"
                          >
                            Mobile Number
                          </label>
                          <Input
                            disabled={verify}
                            id="mobile"
                            value={phoneNumber}
                            placeholder="Input number"
                            onChange={(e) => {
                              dispatch(setPhoneNumber(e.target.value));
                              setErrors((prev) => ({
                                ...prev,
                                phoneNumber: "",
                              }));
                            }}
                            className={`w-full bg-[#F9F9F9] border-none focus:outline-none focus:border-none outline-none !text-[10px] ${
                              verify ? "bg-[#D9D9D9] font-bold" : "font-light"
                            }`}
                          />
                          {/* Error for phone number */}
                          {errors.phoneNumber && (
                            <p className="text-red-500 text-xs mt-1">
                              {errors.phoneNumber}
                            </p>
                          )}
                        </div>
                      </div>

                      {verify && (
                        <motion.div
                          key="step2"
                          initial={{ opacity: 0, x: -20 }}
                          animate={{ opacity: 1, x: 0 }}
                          exit={{ opacity: 0, x: 20 }}
                          transition={{ duration: 0.3 }}
                          className="grid grid-cols-1 sm:grid-cols-2 gap-6 font-poppins"
                        >
                          <div className="md:flex-1">
                            <label
                              htmlFor="full name"
                              className="block text-[12px] text-black mb-1 font-[400px]"
                            >
                              Full Name
                            </label>
                            <Input
                              id="full name"
                              placeholder="Full Name"
                              readOnly
                              disabled
                              value={fullName}
                              className="w-full bg-[#D9D9D9] text-black font-bold !text-[10px] border-none focus:outline-none focus:border-none outline-none"
                            />
                          </div>

                          <div className="md:flex-1 text-[10px]">
                            <label
                              htmlFor="date of birth"
                              className="block font-[400px] text-black mb-1 text-[12px]"
                            >
                              Date of Birth
                            </label>
                            <Input
                              id="date of birth"
                              placeholder="Date of Birth"
                              readOnly
                              disabled
                              value={dateOfBirth}
                              className="w-full bg-[#D9D9D9] text-black font-bold border-none focus:outline-none focus:border-none outline-none !text-[10px]"
                            />
                          </div>

                          <div>
                            <label
                              htmlFor="gender"
                              className="block font-[400px] text-black mb-1 text-[12px]"
                            >
                              Gender
                            </label>
                            <Input
                              id="gender"
                              placeholder="Gender"
                              readOnly
                              disabled
                              value={gender}
                              className="w-full bg-[#D9D9D9] !text-black font-bold border-none focus:outline-none focus:border-none outline-none !text-[10px]"
                            />
                          </div>
                        </motion.div>
                      )}

                      {!verify && (
                        <div>
                          <Button
                            disabled={isLoading}
                            // onClick={() => setVerify(true)}
                            onClick={() => handleVerification()}
                            className="bg-[#FB4F4F] hover:bg-[#FB4F4F]/85 text-white text-[12px] font-bold cursor-pointer"
                          >
                            {isLoading ? <LoadingSpinner /> : "Verify"}
                          </Button>
                        </div>
                      )}
                    </motion.div>
                  )}

                  {currentStep === 2 && (
                    <motion.div
                      key="step2"
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      exit={{ opacity: 0, x: 20 }}
                      transition={{ duration: 0.3 }}
                      className="grid grid-cols-1 sm:grid-cols-2 gap-6 text-[#000000] font-poppins"
                    >
                      <div>
                        <CustomSelect
                          value={maritalStatus}
                          onChange={(val) => {
                            dispatch(setMaritalStatus(val));
                            setErrors((prev) => ({
                              ...prev,
                              maritalStatus: "",
                            }));
                          }}
                          options={maritalOptions}
                          label="Marital Status"
                          placeholder="Please select an option"
                        />
                        {errors.maritalStatus && (
                          <p className="text-red-500 text-xs mt-1">
                            {errors.maritalStatus}
                          </p>
                        )}
                      </div>

                      <div>
                        <CustomSelect
                          value={heightRange}
                          onChange={(val) => {
                            dispatch(setHeightRange(val));
                            setErrors((prev) => ({ ...prev, heightRange: "" }));
                          }}
                          options={heightOptions}
                          label="Height Range"
                          placeholder="Please select an option"
                        />
                        {errors.heightRange && (
                          <p className="text-red-500 text-xs mt-1">
                            {errors.heightRange}
                          </p>
                        )}
                      </div>

                      <div>
                        <CustomSelect
                          value={weightRange}
                          onChange={(val) => {
                            dispatch(setWeightRange(val));
                            setErrors((prev) => ({ ...prev, weightRange: "" }));
                          }}
                          options={weightOptions}
                          label="Weight Range"
                          placeholder="Please select an option"
                        />
                        {errors.weightRange && (
                          <p className="text-red-500 text-xs mt-1">
                            {errors.weightRange}
                          </p>
                        )}
                      </div>

                      <div>
                        <CustomSelect
                          value={ethnicity}
                          onChange={(val) => {
                            dispatch(setEthnicity(val));
                            setErrors((prev) => ({ ...prev, ethnicity: "" }));
                          }}
                          options={ethnicityOptions}
                          label="Ethnicity"
                          placeholder="Please select an option"
                        />
                        {errors.ethnicity && (
                          <p className="text-red-500 text-xs mt-1">
                            {errors.ethnicity}
                          </p>
                        )}
                      </div>

                      <div>
                        <CustomSelect
                          value={genotype}
                          onChange={(val) => {
                            dispatch(setGenotype(val));
                            setErrors((prev) => ({ ...prev, genotype: "" }));
                          }}
                          options={genotypeOptions}
                          label="Genotype"
                          placeholder="Please select an option"
                        />
                        {errors.genotype && (
                          <p className="text-red-500 text-xs mt-1">
                            {errors.genotype}
                          </p>
                        )}
                      </div>

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

                      <div className="">
                        <CustomSelect
                          value={religions}
                          subValue={subReligions}
                          onChange={handleReligionChange}
                          options={religionOptions}
                          label="Religion"
                          placeholder="Please select an option"
                        />
                        {errors.religions && (
                          <p className="text-red-500 text-xs mt-1">
                            {errors.religions}
                          </p>
                        )}
                      </div>
                    </motion.div>
                  )}

                  {currentStep === 3 && (
                    <motion.div
                      key="step3"
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      exit={{ opacity: 0, x: 20 }}
                      transition={{ duration: 0.3 }}
                      className="space-y-6 text-[#000000] font-poppins"
                    >
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                        <div className="md:flex-1 my-2">
                          <label
                            htmlFor="house-number"
                            className="block text-[12px] text-black font-[400px] mb-1"
                          >
                            House Number
                          </label>
                          <Input
                            id="house-number"
                            placeholder="House Number"
                            value={houseNumber}
                            onChange={(e) => {
                              dispatch(setHouseNumber(e.target.value));
                              if (errors.houseNumber) {
                                setErrors((prev) => ({
                                  ...prev,
                                  houseNumber: "",
                                }));
                              }
                            }}
                            className={`w-full bg-[#F9F9F9] ${
                              errors.houseNumber
                                ? "border border-red-500"
                                : "border-none"
                            } focus:outline-none outline-none !text-[10px] text-black`}
                          />
                          {errors.houseNumber && (
                            <p className="text-red-500 text-xs mt-1">
                              {errors.houseNumber}
                            </p>
                          )}
                        </div>

                        <div className="md:flex-1 my-2">
                          <label
                            htmlFor="street-name"
                            className="block text-[12px] mb-1 text-black font-[400px]"
                          >
                            Street Name
                          </label>
                          <Input
                            id="street-name"
                            placeholder="Street name"
                            value={streetName}
                            onChange={(e) => {
                              dispatch(setStreetName(e.target.value));
                              if (errors.streetName) {
                                setErrors((prev) => ({
                                  ...prev,
                                  streetName: "",
                                }));
                              }
                            }}
                            className={`w-full bg-[#F9F9F9] ${
                              errors.streetName
                                ? "border border-red-500"
                                : "border-none"
                            } focus:outline-none outline-none !text-[10px] text-black`}
                          />
                          {errors.streetName && (
                            <p className="text-red-500 text-xs mt-1">
                              {errors.streetName}
                            </p>
                          )}
                        </div>

                        <div className="md:flex-1 my-2">
                          <label
                            htmlFor="landmark"
                            className="block text-[12px] mb-1"
                          >
                            Land Mark
                          </label>
                          <Input
                            id="landmark"
                            placeholder="Land mark"
                            value={landmark}
                            onChange={(e) => {
                              dispatch(setLandmark(e.target.value));
                              if (errors.landmark) {
                                setErrors((prev) => ({
                                  ...prev,
                                  landmark: "",
                                }));
                              }
                            }}
                            className="w-full bg-[#F9F9F9] border-none focus:outline-none focus:border-none outline-none !text-[10px]"
                          />
                          {errors.landmark && (
                            <p className="text-red-500 text-xs mt-1">
                              {errors.landmark}
                            </p>
                          )}
                        </div>

                        <div className="md:flex-1 my-2">
                          <label
                            htmlFor="postal-code"
                            className="block text-[12px] mb-1"
                          >
                            Postal code
                          </label>
                          <Input
                            id="postal-code"
                            placeholder="Postal code"
                            value={postcode}
                            onChange={(e) => {
                              dispatch(setPostcode(e.target.value));
                              if (errors.postcode) {
                                setErrors((prev) => ({
                                  ...prev,
                                  postcode: "",
                                }));
                              }
                            }}
                            className={`w-full bg-[#F9F9F9] ${
                              errors.postcode
                                ? "border border-red-500"
                                : "border-none"
                            } focus:outline-none outline-none !text-[10px] text-black`}
                          />
                          {errors.postcode && (
                            <p className="text-red-500 text-xs mt-1">
                              {errors.postcode}
                            </p>
                          )}
                        </div>

                        <div className="md:flex-1 my-2">
                          <label
                            htmlFor="country"
                            className="block text-[12px] mb-1"
                            hidden
                          >
                            Country
                          </label>
                          <CustomSelect
                            value={country}
                            onChange={(val) => {
                              dispatch(setCountry(val));
                              setErrors((prev) => ({ ...prev, country: "" }));
                            }}
                            options={countryOptions}
                            label="Country"
                            placeholder="Please select an option"
                          />
                          {errors.country && (
                            <p className="text-red-500 text-xs mt-1">
                              {errors.country}
                            </p>
                          )}
                        </div>

                        <div className="md:flex-1 my-2">
                          <label
                            htmlFor="state"
                            className="block text-[12px] mb-1"
                            hidden
                          >
                            State
                          </label>

                          <CustomSelect
                            value={state}
                            onChange={(val) => {
                              dispatch(setState(val));
                              setErrors((prev) => ({ ...prev, state: "" }));
                            }}
                            options={stateOptions}
                            label="State"
                            placeholder="Please select an option"
                          />

                          {errors.state && (
                            <p className="text-red-500 text-xs mt-1">
                              {errors.state}
                            </p>
                          )}
                        </div>

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

                          <CustomSelect
                            value={lga}
                            onChange={(val) => {
                              dispatch(setLGA(val));
                              const isValid = lgaOptions?.some(
                                (opt) =>
                                  opt.value.toLowerCase() === val.toLowerCase()
                              );
                              console.log(isValid);

                             
                            }}
                            options={lgaOptions}
                            placeholder="Select LGA"
                          />

                        </div>
                      </div>
                    </motion.div>
                  )}

                  {currentStep === 4 && (
                    <motion.div
                      key="step4"
                      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="grid grid-cols-1 sm:grid-cols-2 gap-6 font-poppins">
                        <RenderMultiSelectField
                          label="Hobbies"
                          field="hobbies"
                          options={hobbiesOptions.map((option) => option.label)} // extract string labels
                          value={
                            setupDetails["hobbies&interests"].hobbies || []
                          }
                          clickAction={openMultiSelect}
                          error={errors.hobbies}
                        />

                        <RenderMultiSelectField
                          label="Interests"
                          field="interests"
                          options={interestsOptions.map(
                            (option) => option.label
                          )} // extract string labels
                          value={
                            setupDetails["hobbies&interests"].interests || []
                          }
                          clickAction={openMultiSelect}
                          error={errors.interests}
                        />

                        <RenderMultiSelectField
                          label="Languages Spoken"
                          field="languages"
                          options={languagesOptions.map(
                            (option) => option.label
                          )}
                          value={
                            setupDetails["hobbies&interests"].languages || []
                          }
                          clickAction={openMultiSelect}
                          error={errors.languages}
                        />
                      </div>

                      {showMultiSelect && (
                        <>
                          <Overlay func={() => {}} />
                          <div className="fixed inset-0 z-50 flex items-center justify-center">
                            <MultiSelect
                              options={currentOptions}
                              onSave={(selectedValues) => {
                                handleMultiSelection(
                                  selectedValues.length > 0
                                    ? selectedValues
                                    : []
                                );
                              }}
                              onCancel={() => setShowMultiSelect(false)}
                              // initialSelections={
                              //   setupDetails["hobbies&interests"].hobbies || []
                              // }
                            />
                          </div>
                        </>
                      )}
                    </motion.div>
                  )}

                  {(currentStep > 1 || (verify && currentStep === 1)) && (
                    <div className="flex space-x-4 my-5">
                      <Button
                        onClick={goToPreviousStep}
                        variant="outline"
                        className="bg-[#FB4F4F] hover:bg-[#FB4F4F]/85 hover:text-white text-white cursor-pointer"
                      >
                        Back
                      </Button>
                      <Button
                        onClick={handleNext}
                        disabled={isLoading}
                        className="bg-[#FB4F4F] hover:bg-[#FB4F4F]/85 text-white cursor-pointer"
                      >
                        {isLoading ? (
                          <LoadingSpinner />
                        ) : currentStep === 4 ? (
                          "Finish"
                        ) : (
                          "Continue"
                        )}
                      </Button>
                    </div>
                  )}
                </AnimatePresence>
              </div>
            </div>
          )}

          {finish && (
            <>
              <Overlay func={() => {}} />
              <div className="fixed inset-0 z-30 flex items-center justify-center">
                <Edit
                  selectedStep={"match"}
                  onSave={savematchProfileValues}
                  onCancel={() => setFinish(false)}
                  formData={{}}
                  setFormData={() => {}}
                  back={() => handleBack()}
                  weightOptions={weightOptions}
                  heightOptions={heightOptions}
                  maritalOptions={maritalOptions}
                  genotypeOptions={genotypeOptions}
                  ethnicityOptions={ethnicityOptions}
                  religionOptions={religionOptions}
                  languagesOption={languagesOptions}
                  ageOptions={ageOptions}
                  countryOptions={countryOptions}
                  stateOptions={stateOptions}
                  hobbiesOptions={hobbiesOptions}
                  interestsOptions={interestsOptions}
                  relationshipOptions={relationshipOptions}
                />
              </div>
            </>
          )}

          <div className="mt-8 text-center text-gray-500">
            Nothing to see here
          </div>
        </div>
      </div>
    </AuthGuard>
  );
}
