"use client";
import { TOKEN_NAME } from "@/constance";
import Image from "next/image";
import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setToken } from "../slices/tokenSlice";
import {
  useBookAppointment,
  useOnlineBookAppointment,
} from "@/utils/AppointmentBookApi";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { getApi, getAPIAuth } from "@/services/apiservice";
import {
  API_GET_CLINIC_DETAILS,
  API_GET_SPECIALIZATION,
  API_GET_DOCTOR_BY_CLINIC,
  API_GET_SPECIALIZATION_BY_SLUG,
  API_GET_CITY,
} from "@/utils/APIConstant";
import { useQuery } from "@tanstack/react-query";
import PatientModal from "../otp/PatientModal";
import { fetchUserCredential, setUserCredential } from "../slices/userCredencial";
import {
  setClinicData,
  setFooterData,
  setSpecializationData,
} from "../slices/ClinicDetailSlice";
import ViewPlansModals from "@/utils/ViewPlansModals";
import { setIsViewPlans } from "../slices/IsViewPlans";
import AccountDropdown from "./AccountDropdown";
import { setRating } from "../slices/loginSlice";
import SignOutModal from "./SignOutModal";
import { clearRoutes } from "@/utils/routeConstant";
import { useInfiniteData } from "@/utils/useInfiniteQuery";
import InfiniteScroll from "react-infinite-scroll-component";
import { AllPageLoader } from "@/utils/Loader";
import { toast } from "react-toastify";
import { FaChevronDown } from "react-icons/fa";
import { IoLocationSharp } from "react-icons/io5";
import { setCityList, setSelectedCity } from "../slices/citySlice";
import { slugGenerator, withBasePath } from "@/utils/comman/Comman";
import { slugify } from "@/services/comman/comman";
// import { cookies } from "next/headers";

const Header = () => {
  const dispatch = useDispatch();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModal, setIsModal] = useState(false);
  console.log({ isModal }, "Rthyrtyrtyrtyrty")
  const [isSpecialLinkOpen, setIsSpecialLinkOpen] = useState(false);
  const [doctorLinks, setDoctorsLinkOpen] = useState(false);
  const [selectedSlug, setSelectedSlug] = useState(null);
  const footerDataDetail = useSelector(
    (state) => state?.clinicDetails?.footerData
  );
  const { selectedCity, cityList } = useSelector(
    (state) => state?.cityDetails
  )
  const ProfileCredential = useSelector(
    (state) => state?.ProfileCredencial?.Credential
  );
  const citySlug = slugGenerator(selectedCity?.name);
  const [searchQuery, setSearchQuery] = useState("");
  const [toggle, setToggle] = useState(false);
  const [locationOpen, setLocationOpen] = useState(false);
  const [citySearch, setCitySearch] = useState("");
  const searchRef = useRef(null);
  const cityRef = useRef(null);
  const router = useRouter();
  const param = usePathname();
  const Token = useSelector((state) => state?.userCredential?.token);
  function useDebounce(value, delay = 400) {
    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(() => {
      const handler = setTimeout(() => {
        setDebouncedValue(value);
      }, delay);

      return () => clearTimeout(handler);
    }, [value, delay]);

    return debouncedValue;
  }
  const debouncedSearch = useDebounce(searchQuery, 400);
  const debouncedSearchForCity = useDebounce(citySearch, 400);

  useEffect(() => {
    function handleClickOutside(e) {
      if (searchRef.current && !searchRef.current.contains(e.target)) {
        setToggle(false);
      }
      if (cityRef.current && !cityRef.current.contains(e.target)) {
        setLocationOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleSpecializationClick = (specialization) => {
    console.log("Clicked Slug:", specialization); // Log clicked specialization directly
    setSelectedSlug(specialization); // Set the state with the clicked specialization
  };
  useEffect(() => {
    console.log("Updated Selected Slug:", selectedSlug); // Logs the selectedSlug after it's updated
  }, [selectedSlug]); // This runs whenever selectedSlug changes
  // const cookiesToken = cookies().get(TOKEN_NAME)?.value;
  // console.log("cookiesTokencookiesToken" , cookiesToken);
  const {
    infiniteData: specializationData,
    hasNextPage: specializationHasNextPage,
    fetchNextPage: fetchSpecializationNextPage,
  } = useInfiniteData({
    queryKey: "specialization-infinity-list",
    apiEndpoint: API_GET_SPECIALIZATION,
    // queryParams: { search: specilizationSeachData },
    Token,
    perPage: 5,
  });
  useEffect(() => {
    const getCookie = (name) => {
      const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
      return match ? match[2] : null;
    };

    const token = getCookie(TOKEN_NAME);
    if (!token) {
      console.log("Token not found, clearing local storage...");
      sessionStorage.clear();
      localStorage.removeItem(TOKEN_NAME);
      dispatch(setToken(""));
      document.cookie = `${TOKEN_NAME}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`;
      // router.push("/login");
      // router.push("/login");
      setShowCloseBtn(false);
      dispatch(setRating({ key: `` }));
      setIsModalOpen(false);
    }
  }, [dispatch, router]);
  useEffect(() => {
    const storedOfflineData = sessionStorage.getItem("AppointmentCredential");
    if (storedOfflineData && clearRoutes.includes(param)) {
      sessionStorage.removeItem("AppointmentCredential");
    }
  }, [param]);
  useEffect(() => {
    dispatch(setToken(localStorage.getItem(TOKEN_NAME)));
  }, [dispatch]);

  const ModalViewPlansDetails = useSelector(
    (state) => state?.PlansDetails.IsViewPlans
  );
  const { mutate: submitOnlineAppointment } = useOnlineBookAppointment(Token);
  const handleLogout = () => {
    localStorage.removeItem(TOKEN_NAME);
    dispatch(setToken(""));
    document.cookie = `${TOKEN_NAME}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`;
    router.push("/login");
    localStorage.removeItem("appointmentDetails");
    // router.push("/login");
    setShowCloseBtn(false);
    dispatch(setRating({ key: `` }));
    setIsModalOpen(false);
  };
  const { mutate: submitAppointment } = useBookAppointment(Token);
  const { data: doctorData, isLoading: isDoctorLoading } = useQuery({
    queryKey: ["doctor-list"],
    queryFn: () =>
      getApi(
        `${API_GET_DOCTOR_BY_CLINIC}?domain=${process.env.NEXT_PUBLIC_DOMAIN}&isExpert=true`
      ),
  });
  const { data: searchDoctorData, isLoading: isSearchDoctorLoading } = useQuery(
    {
      queryKey: ["search-doctor-list", debouncedSearch],
      queryFn: () =>
        getApi(
          `${API_GET_DOCTOR_BY_CLINIC}?domain=${process.env.NEXT_PUBLIC_DOMAIN}&search=${debouncedSearch}`
        ),
    }
  );
  const searchDoctorList = useMemo(() => {
    return searchDoctorData?.data?.documents || [];
  }, [searchDoctorData]);

  //specializationData
  // api.js or wherever your API helpers are
  const getSpecializationBySlug = (slug) => {
    return getApi(`${API_GET_SPECIALIZATION_BY_SLUG}?slug=${slug}`);
  };
  const { data: specializationDetails, isLoading: isSpecializationLoading } =
    useQuery({
      queryKey: ["specialization-details", selectedSlug],
      queryFn: () => getSpecializationBySlug(selectedSlug),
      enabled: !!selectedSlug, // Ensures the query runs only when selectedSlug is truthy
      refetchOnWindowFocus: false,
      cacheTime: 1000 * 60 * 5,
    });

  const { data: clinicDetails } = useQuery({
    queryKey: ["get-clinic-details"],
    queryFn: () =>
      getApi(
        `${API_GET_CLINIC_DETAILS}?domain=${process.env.NEXT_PUBLIC_DOMAIN}`
      ),
    staleTime: 5 * 60 * 1000,
  });
  useEffect(() => {
    dispatch(setClinicData(clinicDetails?.data));
  }, [clinicDetails, dispatch]);

  const { data: footerData } = useQuery({
    queryKey: ["get-footer-content"],
    queryFn: () =>
      getAPIAuth(`content/getFooter?domain=${process.env.NEXT_PUBLIC_DOMAIN}`),
    staleTime: 5 * 60 * 1000,
  });

  useEffect(() => {
    if (footerData?.data?.success) {
      const info = footerData.data.data;
      const baseUrl = footerData.data.baseUrl;

      const updatedInfo = {
        ...info,
        footerLogo: info?.footerLogo ? `${baseUrl}${info?.footerLogo}` : null,
        headerLogo: info?.headerLogo ? `${baseUrl}${info?.headerLogo}` : null,
      };
      dispatch(setFooterData(updatedInfo));
    }
  }, [footerData]);

  useEffect(() => {
    const storedAppointmentString = localStorage.getItem("appointmentDetails");
    const storedOnlineAppointmentString = localStorage.getItem(
      "appointmentDetailsOnline"
    );
    const storedOnlineAppointment = JSON.parse(storedOnlineAppointmentString);
    const storedAppointment = JSON.parse(storedAppointmentString);
    if (storedAppointment && ProfileCredential?.isRegister) {
      // alert("hii");
      // router.push("/appointment?type=online");
      submitAppointment({
        doctorId: storedAppointment?.doctorId,
        slot: {
          start: storedAppointment?.slot?.start,
          end: storedAppointment?.slot?.end,
        },
        date: storedAppointment?.date,
        slotType: storedAppointment?.slotType,
        amount: storedAppointment?.amount,
      });
    }

    console.log("storedOnlineAppointment", storedOnlineAppointment);

    if (storedOnlineAppointment && ProfileCredential?.isRegister) {
      submitOnlineAppointment(storedOnlineAppointment);
    }
  }, [Token, ProfileCredential]);

  console.log({ specializationData });
  console.log(specializationData, "specializationDetails?.specialization");

  const [showCloseBtn, setShowCloseBtn] = useState(false);

  useEffect(() => {
    const appointmentUrl = localStorage.getItem("appointmentUrl");
    if (appointmentUrl && Token) {
      router.push(appointmentUrl);
      localStorage.removeItem("appointmentUrl");
    }
  }, [Token]);

  const {
    data: cityData,
    isLoading: cityIsLoading,
  } = useQuery({
    queryKey: ["city-list", debouncedSearchForCity],
    queryFn: () => {
      return getAPIAuth(
        `${API_GET_CITY}?search=${debouncedSearchForCity}&isBlocked=true`,
        Token
      );
    }
  });
  console.log(cityData?.data?.data?.documents, "Rtyhrtyrtyrtyrtyrt")
  useEffect(() => {
    if (cityData?.data?.data?.documents?.length > 0) {
      const cityList = cityData?.data?.data?.documents || [];
      dispatch(setCityList(cityList));
    }
  }, [cityData]);

  useEffect(() => {
    const selectedCity = localStorage.getItem("selectedCity");
    if (selectedCity) {
      dispatch(setSelectedCity(JSON.parse(selectedCity)));
    }
  }, [])

  useEffect(() => {
    if (Token) {
      dispatch(fetchUserCredential(Token))
    }
  }, [Token])

  useEffect(() => {
    if (ProfileCredential?.isRegister == false) {
      setIsModal(true)
    }
  }, [ProfileCredential, param]);

  return (
    <>
      <div className="bg-white shadow-sm py-5 fixed top-0 z-50 w-full">
        <div className="max-w-7xl px-4 lg:px-8 mx-auto flex  flex-wrap justify-between w-full">
          <Link href="/" className="sm:h-[50px] h-[38px] w-[174px] order-1 md:order-1 shrink-0">
            <Image
              width={174}
              height={42}
              src={
                // footerDataDetail?.headerLogo ||
                withBasePath("/assets/img/logo/medivoralogo.svg")
              }
              alt="logo main"
              className="h-full  max-sm:object-cover object-contain w-full "
            />
          </Link>

          <div className="flex mt-2 md:mt-0 justify-center order-3 relative md:order-2 items-center">
            <div ref={searchRef} className="relative md:w-[380px]">
              <input
                type="text"
                placeholder="Search doctor by name..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onClick={() => setToggle(true)}
                className="w-full border border-gray-300 rounded-full px-4 py-2 pr-10 text-sm focus:outline-none focus:ring-2 focus:ring-[#7b2cbf]"
              />
              {searchQuery && (
                <button
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-black"
                  onClick={(e) => {
                    e.stopPropagation();
                    setSearchQuery("");
                    setToggle(false);
                  }}
                >
                  ✕
                </button>
              )}
              {toggle && (
                <div className="absolute top-12 w-full bg-white shadow-lg rounded-lg border z-50">
                  {searchDoctorList?.length > 0
                    ? searchDoctorList?.map((doc) => (
                      <div
                        key={doc?._id}
                        className="px-4 py-2 hover:bg-gray-100 cursor-pointer"
                        onClick={(e) => {
                          e.stopPropagation();
                          setSearchQuery(doc?.name);
                          setToggle(false);
                          router.push(`/doctors/${slugify(doc?.name)}-${slugify(doc?.profileSpecialization)}-${doc?._id}`);
                        }}
                      >
                        <p className="font-medium text-sm">{doc?.name}</p>
                        <p className="text-xs text-gray-500">
                          {doc?.profileSpecialization}, Exp:-{doc?.experience}
                        </p>
                      </div>
                    ))
                    : searchQuery.trim() !== "" && (
                      <div className="px-4 py-3 text-sm text-gray-500 text-center">
                        No doctor found
                      </div>
                    )}
                </div>
              )}
            </div>
          </div>
          <div ref={cityRef} className="flex items-center md:mt-0 mt-2 order-4 space-x-1 md:order-3 mr-2 relative">
            {" "}
            <IoLocationSharp size={18} />{" "}
            <button
              onClick={() => setLocationOpen(!locationOpen)}
              className="flex items-center"
            >
              {" "}
              <span className="text-sm text-nowrap font-medium">{selectedCity?.name || "Select City"}</span>{" "}
              <FaChevronDown size={12} className="ml-1" />{" "}
            </button>{" "}
            {locationOpen && (
              <div className="absolute top-full left-0 right-auto max-h-68 overflow-y-auto w-auto mt-2 md:w-60 bg-white border rounded shadow z-50">
                {" "}
                <input
                  type="text"
                  placeholder="Search city..."
                  className="w-full p-2 border-b outline-none"
                  value={citySearch}
                  onChange={(e) => setCitySearch(e.target.value)}
                />{" "}
                {cityList?.length > 0 ? (
                  <ul className="max-h-40 overflow-auto">
                    {" "}
                    {cityList?.map((city) => (
                      <li
                        key={city._id || city.name}
                        className="p-2 hover:bg-gray-100 cursor-pointer"
                        onClick={(e) => {
                          e.stopPropagation();
                          setLocationOpen(false);
                          const payload = {
                            _id: city?._id,
                            name: city?.name
                          }
                          dispatch(setSelectedCity(payload));
                          localStorage.setItem("selectedCity", JSON.stringify(payload));
                        }}
                      >
                        {" "}
                        {city.name}{" "}
                      </li>
                    ))}{" "}
                  </ul>
                ) : (
                  <div className="p-2 text-sm text-gray-500">
                    No cities found
                  </div>
                )}{" "}
              </div>
            )}{" "}
          </div>
          <ul className="items-center md:order-4  list-none xl:flex gap-3  text-sm text-slate-800 font-bold *:duration-300 hidden ">
            <li className="hover:text-[#7b2cbf] w-fit relative before:absolute before:border-b-2 before:border-[#7b2cbf] before:w-full before:left-0 before:bottom-0 before:-translate-x-full before:hover:translate-x-0 before:duration-500 overflow-hidden !z-50">
              <Link href="/">Home</Link>
            </li>
            {/* <li className="hover:text-[#7b2cbf] relative before:absolute before:border-b-2 before:border-[#7b2cbf] before:w-full before:left-0 before:bottom-0 before:-translate-x-full before:hover:translate-x-0 before:duration-500 overflow-hidden !z-50">
              <Link href="/about">About Us</Link>
            </li> */}
            {specializationData?.length === 1 ? (
              // If only one specialization, show it directly in header
              <li className="hover:text-[#7b2cbf] w-fit relative before:absolute before:border-b-2 before:border-[#7b2cbf] before:w-full before:left-0 before:bottom-0 before:-translate-x-full before:hover:translate-x-0 before:duration-500 overflow-hidden !z-50">
                <Link
                  href={`/specialization/${specializationData[0]?.slug}`}
                >
                  {specializationData[0]?.specialization || "Specialization"}
                </Link>
              </li>
            ) : (
              // If multiple, show dropdown
              <li
                className="relative w-fit group z-50 hover:text-[#7b2cbf] cursor-pointer"
                onMouseEnter={() => setIsSpecialLinkOpen(true)}
                onMouseLeave={() => setIsSpecialLinkOpen(false)}
              >
                <span className="block py-2">Specialization</span>

                {isSpecialLinkOpen && (
                  <div
                    id="scrollableDive"
                    className="h-[150px] absolute overflow-y-auto w-[288px] border-t-2 border-t-[#7b2cbf] left-0 right-auto p-5 bg-white shadow-lg rounded-2xl z-50 transition-all duration-300"
                  >
                    {specializationData.length > 0 ? (
                      <InfiniteScroll
                        dataLength={specializationData?.length}
                        next={fetchSpecializationNextPage}
                        hasMore={specializationHasNextPage}
                        loader={
                          <div className="text-center py-4">
                            <h4>
                              <AllPageLoader />
                            </h4>
                          </div>
                        }
                        scrollableTarget="scrollableDive"
                      >
                        <ul className="*:whitespace-nowrap">
                          <div className="grid grid-cols-3 sm:grid-cols-3 lg:grid-cols-1">
                            {specializationData?.map(
                              (specialization, index) => (
                                <li key={index}>
                                  <Link
                                    href={`/specialization/${specialization?.slug}${citySlug ? `/${citySlug}` : ''}`}
                                    className="block text-sm hover:bg-[#7b2cbf] px-2 py-3 border-b hover:text-white rounded-md transition-all"
                                    onClick={() =>
                                      handleSpecializationClick(
                                        specialization?.slug
                                      )
                                    }
                                  >
                                    {specialization?.specialization ||
                                      "No Name"}
                                  </Link>
                                </li>
                              )
                            )}
                          </div>
                        </ul>
                      </InfiniteScroll>
                    ) : (
                      <div className="text-center text-gray-500 col-span-full">
                        No specializations found.
                      </div>
                    )}
                  </div>
                )}
              </li>
            )}

            <li
              className="relative group z-50 hover:text-[#7b2cbf] cursor-pointer"
              onMouseEnter={() => setDoctorsLinkOpen(true)}
              onMouseLeave={() => setDoctorsLinkOpen(false)}
            >
              <span className="block  py-2">Doctors</span>

              {doctorLinks && (
                <div className="absolute border-t-2 border-t-[#7b2cbf] left-0 right-auto w-[288px] max-h-[300px] overflow-y-auto p-5 bg-white shadow-lg rounded-2xl z-50 transition-all duration-300">
                  {isDoctorLoading ? (
                    <div className="text-center py-4 text-gray-500">
                      Loading doctors...
                    </div>
                  ) : doctorData?.data?.documents?.length ? (
                    <ul className="*:whitespace-nowrap">
                      <div className="grid grid-cols-3 sm:grid-cols-3 lg:grid-cols-1">
                        {doctorData?.data?.documents?.map((doctor) => (
                          <li key={doctor._id}>
                            <Link
                              href={`/doctors/${slugify(doctor?.name)}-${slugify(doctor?.profileSpecialization)}-${doctor._id}`}
                              className="block text-sm hover:bg-[#7b2cbf] px-2 py-3 border-b hover:text-white rounded-md transition-all"
                            >
                              {doctor.name || "Unnamed Doctor"}
                            </Link>
                          </li>
                        ))}
                      </div>
                    </ul>
                  ) : (
                    <div className="text-center text-gray-500 col-span-full">
                      No doctors found.
                    </div>
                  )}
                </div>
              )}
            </li>
            {/* <li className="hover:text-[#7b2cbf] relative before:absolute before:border-b-2 before:border-[#7b2cbf] before:w-full before:left-0 before:bottom-0 before:-translate-x-full before:hover:translate-x-0 before:duration-500 overflow-hidden !z-50">
              <Link href="/sexologist-consultation">Doctors</Link>
            </li> */}

            {Token ? (
              <>
                {/* <li className="hover:text-[#7b2cbf] relative before:absolute before:border-b-2 before:border-[#7b2cbf] before:w-full before:left-0 before:bottom-0 before:-translate-x-full before:hover:translate-x-0 before:duration-500 overflow-hidden !z-50">
                  <Link href="/patientsDetails">Patients</Link>
                </li> */}
                <li className="gap-2 flex">
                  <Link
                    href={"/appointment?type=offline&slotType=onVisit"}
                    className="bg-[#7b2cbf] px-4 py-1.5 text-white rounded-lg"
                  >
                    Schedule Appointment
                  </Link>

                  <AccountDropdown
                    parentclassName="hidden sm:block"
                    handleLogout={handleLogout}
                    setIsModalOpen={setIsModalOpen}
                  />
                </li>
              </>
            ) : (
              <>
                <li className="gap-2 flex">
                  <Link
                    href="/login"
                    className="border-[#7b2cbf] border px-4 py-1.5 text-[#7b2cbf] rounded-lg"
                  >
                    Login
                  </Link>
                  <Link
                    href="/appointment?type=offline&slotType=onVisit"
                    className="bg-[#7b2cbf] px-4 py-1.5 text-white rounded-lg"
                  >
                    Appointment
                  </Link>
                  {/* <Link
                    href="/addDoctor"
                    className="bg-[#7b2cbf] px-4 py-1.5 text-white rounded-lg"
                  >
                    Add Doctor
                  </Link> */}
                </li>
              </>
            )}
          </ul>
          <div className="flex items-center space-x-4 order-2 xl:hidden">
            <div className="flex xl:hidden">
              <label
                htmlFor="sideToggle"
                className="-m-2.5 inline-flex items-center justify-center rounded-md  text-[#7b2cbf] group-[]/nav:text-black"
              >
                <span className="sr-only">Open menu</span>
                {showCloseBtn ? (
                  <svg
                    className="size-7 text-[#7b2cbf] "
                    stroke="currentColor"
                    fill="currentColor"
                    strokeWidth="0"
                    viewBox="0 0 512 512"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="m289.94 256 95-95A24 24 0 0 0 351
                   127l-95 95-95-95a24 24 0 0 0-34 34l95 95-95 
                   95a24 24 0 1 0 34 34l95-95 95 95a24 24 0 0 0
                    34-34z"
                    ></path>
                  </svg>
                ) : (
                  <svg
                    className="size-7"
                    fill="none"
                    viewBox="0 0 24 24"
                    strokeWidth="1.5"
                    stroke="currentColor"
                    aria-hidden="true"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"
                    ></path>
                  </svg>
                )}
              </label>
            </div>
            <div className=" ">
              {Token ? (
                <div className="flex items-center">
                  <AccountDropdown
                    parentclassName="hidden sm:block"
                    handleLogout={handleLogout}
                    setIsModalOpen={setIsModalOpen}
                  />
                  <span className="text-white font-semibold ml-3 hidden">
                    {ProfileCredential?.name}
                  </span>
                </div>
              ) : (
                ""
              )}

              {/* <div className="mt-4 hidden">
                <Link
                  href="/profile"
                  className="block text-sm font-bold text-gray-50"
                >
                  Profile
                </Link>
                <Link
                  href="/patientsDetails"
                  className="mt-2 block text-sm font-bold text-gray-50"
                >
                  Patients
                </Link>
                <Link
                  href="/allApointment"
                  className="mt-2 block text-sm font-bold text-gray-50"
                >
                  All Appointments
                </Link>
                <div
                  href="#"
                  onClick={() => setIsModalOpen(true)}
                  className=" cursor-pointer mt-2 block text-sm font-bold text-gray-50"
                >
                  Logout
                </div>
              </div> */}
            </div>
          </div>
        </div>
      </div>
      {/* responsive header */}
      <input
        type="checkbox"
        className="peer hidden lg:hidden"
        id="sideToggle"
        checked={showCloseBtn}
        onChange={() => setShowCloseBtn(!showCloseBtn)}
      />
      <div
        className={`fixed flex flex-col h-screen bg-[#7b2cbf]/90 backdrop-blur-3xl inset-y-0 z-[1011] text-white w-full max-w sm:ring-1 sm:ring-theme1/10 overflow-y-auto select-none transition-all duration-300
    ${showCloseBtn
            ? "translate-y-[78px] opacity-100 "
            : "-translate-y-full opacity-0"
          }
    right-0  lg:hidden
  `}
      >
        <div className=" bg-[#7b2cbf] px-6 py-6 ">
          <div className="mt-6 flow-root flex-fill -mr-4 pr-4">
            <div className="-my-6 divide-y divide-gray-500/10">
              <div className="space-y-2 py-6">
                <div className="flex flex-col gap-5  items-start">
                  <ul className="flex flex-col w-full gap-y-5">
                    <div
                      onClick={() => {
                        router.push("/");
                        setShowCloseBtn(false);
                      }}
                      className="text-base font-bold text-gray-50 cursor-pointer"
                    >
                      Home
                    </div>

                    {/* <div
                      onClick={() => {
                        router.push("/about");
                        setShowCloseBtn(false);
                      }}
                      className="text-sm font-bold text-gray-50"
                    >
                      About Us
                    </div> */}
                    {
                      specializationData?.length > 0 && (
                        <div className="text-base font-bold text-gray-50 cursor-pointer">
                          <input
                            type="checkbox"
                            id="specialization-toggle"
                            className="hidden peer"
                          />

                          {/* Label acts as the button to open/close the dropdown */}
                          <label
                            htmlFor="specialization-toggle"
                            className="cursor-pointer text-base font-bold text-gray-50 flex items-center gap-x-[2px]"
                          >
                            Specialization
                            <svg
                              className="h-6 w-6 ml-auto flex-none text-gray-300"
                              viewBox="0 0 20 20"
                              fill="currentColor"
                              aria-hidden="true"
                            >
                              <path
                                fillRule="evenodd"
                                d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
                                clipRule="evenodd"
                              ></path>
                            </svg>
                          </label>
                          <div className="absolute mt-2 w-48 bg-white shadow-lg rounded-md opacity-0 pointer-events-none transition-all duration-300 peer-checked:opacity-100 peer-checked:static peer-checked:pointer-events-auto z-50">
                            <ul className="divide-y divide-gray-200">
                              {specializationData?.map(
                                (specialization, index) => (
                                  <li key={index} className=" text-black text-sm font-normal px-4 py-2 cursor-pointer">
                                    <Link
                                      href={`/specialization/${specialization?.slug}`}
                                      onClick={() => {
                                        handleSpecializationClick(
                                          specialization?.slug
                                        )
                                        setShowCloseBtn(false);
                                      }}
                                    >
                                      {specialization?.specialization ||
                                        "No Name"}
                                    </Link>
                                  </li>
                                )
                              )}
                            </ul>
                          </div>
                        </div>
                      )
                    }
                    {
                      doctorData?.data?.documents?.length > 0 && (
                        <div className="text-base font-bold text-gray-50 cursor-pointer">
                          <input
                            type="checkbox"
                            id="doctor-toggle"
                            className="hidden peer"
                          />

                          {/* Label acts as the button to open/close the dropdown */}
                          <label
                            htmlFor="doctor-toggle"
                            className="cursor-pointer text-base font-bold text-gray-50 flex items-center gap-x-[2px]"
                          >
                            Doctor
                            <svg
                              className="h-6 w-6 ml-auto flex-none text-gray-300"
                              viewBox="0 0 20 20"
                              fill="currentColor"
                              aria-hidden="true"
                            >
                              <path
                                fillRule="evenodd"
                                d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
                                clipRule="evenodd"
                              ></path>
                            </svg>
                          </label>
                          <div className="absolute mt-2 w-48 bg-white shadow-lg rounded-md opacity-0 pointer-events-none transition-all duration-300 peer-checked:opacity-100 peer-checked:static peer-checked:pointer-events-auto z-50">
                            <ul className="divide-y divide-gray-200">
                              {doctorData?.data?.documents?.map(
                                (doctor, index) => (
                                  <li key={index} className=" text-black text-sm font-normal px-4 py-2 cursor-pointer">
                                    <Link
                                      href={`/doctors/${slugify(doctor?.name)}-${slugify(doctor?.profileSpecialization)}-${doctor._id}`}
                                      onClick={() => {
                                        setShowCloseBtn(false);
                                      }}
                                    >
                                      {doctor?.name ||
                                        "No Name"}
                                    </Link>
                                  </li>
                                )
                              )}
                            </ul>
                          </div>
                        </div>
                      )
                    }
                    {/* <div
                      onClick={() => {
                        router.push("/sexologist-consultation");
                        setShowCloseBtn(false);
                      }}
                      className="text-sm font-bold text-gray-50"
                    >
                      Sexologist Consultation
                    </div> */}
                    {/* <div
                      onClick={() => {
                        router.push("/patientsDetails");
                        setShowCloseBtn(false);
                      }}
                      className="text-sm font-bold text-gray-50"
                    >
                      Patients
                    </div> */}
                    {Token ? (
                      <>
                        <li className="gap-2 flex">
                          {/* <div
                            // href="/./login"
                            className="border-[#7b2cbf] border px-4 py-1.5 text-[#7b2cbf] rounded-lg"
                            onClick={handleLogout}
                          >
                            Logout
                          </div> */}
                          <div
                            // href="/appointment?type=online"
                            onClick={() => {
                              router.push(
                                "/appointment?type=offline&slotType=onCall"
                              );
                              setShowCloseBtn(false);
                            }}
                            className="bg-black px-4 py-1.5 text-white rounded-lg"
                          >
                            Schedule Appointment
                          </div>
                          {/*  */}
                        </li>
                        {/* <div className="px-4 py-5 border-t border-gray-800   xl:block sm:block">
                          <div className="flex items-center">
                            <img
                              className=" border-2 border-[#7b2cbf] h-8 w-8 rounded-full object-cover "
                              src="\assets\img\useravtar.png"
                              alt="Your avatar"
                            />
                            <span className="text-white font-semibold ml-3">
                              {ProfileCredential?.name}
                            </span>
                          </div>

                          <div className="mt-4">
                            <Link
                              href="/profile"
                              className="block text-sm font-bold text-gray-50"
                              onClick={() => setShowCloseBtn(false)}
                            >
                              Profile
                            </Link>
                            <Link
                              href="/patientsDetails"
                              className="mt-2 block text-sm font-bold text-gray-50"
                              onClick={() => setShowCloseBtn(false)}
                            >
                              Patients
                            </Link>
                            <Link
                              href="/allApointment"
                              className="mt-2 block text-sm font-bold text-gray-50"
                              onClick={() => setShowCloseBtn(false)}
                            >
                              All Appointments
                            </Link>
                            <div
                              href="#"
                              onClick={() => {
                                setIsModalOpen(true);
                                setShowCloseBtn(false);
                              }}
                              className=" cursor-pointer mt-2 block text-sm font-bold text-gray-50"
                            >
                              Logout
                            </div>
                          </div>
                        </div> */}
                      </>
                    ) : (
                      <>
                        <li className="gap-2 flex flex-col">
                          <div>
                            <div
                              onClick={() => {
                                router.push("/appointment?type=online");
                                setShowCloseBtn(false);
                              }}
                              className="bg-seco[#7b2cbf]der font-bold  px-7 py-1.5 text-white rounded-lg inline-block"
                            >
                              Appointment
                            </div>
                          </div>

                          <div>
                            {" "}
                            <div
                              onClick={() => {
                                router.push("/login");
                                setShowCloseBtn(false);
                              }}
                              className="border-white border text-white px-7 py-1.5 rounded-lg inline-block "
                            >
                              Login
                            </div>
                          </div>
                          {/* <div
                            // href="/addDoctor"
                            onClick={() => {
                              router.push("/addDoctor");
                              setShowCloseBtn(false);
                            }}
                            className="bg-[#7b2cbf] px-4 py-1.5 text-white rounded-lg"
                          >
                            Add Doctor
                          </div> */}
                        </li>
                      </>
                    )}
                  </ul>
                  <div></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      {isModal && <PatientModal isModal={isModal} setIsModal={setIsModal} />}
      {ModalViewPlansDetails && Token ? (
        <>
          <ViewPlansModals
            isModalOpen={ModalViewPlansDetails}
            setIsModalOpen={setIsViewPlans}
          />
        </>
      ) : (
        <></>
      )}
      {isModalOpen && (
        <SignOutModal
          onClose={() => setIsModalOpen(false)}
          onSignOut={handleLogout}
        />
      )}
    </>
  );
};

export default Header;
