"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { usePathname, redirect } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { fetchSearchValue } from "@/store/search-comp/actions";
import { Button } from "antd";
import { ChevronDown, ChevronRight } from "lucide-react"; // Icons
import axios from "@/utils/axios-config";

// import image1 from "@/";
//import Link from "./Link";
type BottomHeaderProps = {
  isVisible: boolean;
};

const categories = [
  {
    name: "Electronics",
    subcategories: ["Phones", "Laptops", "Accessories"],
  },
  {
    name: "Fashion",
    subcategories: ["Men", "Women", "Kids"],
  },
  {
    name: "Home & Kitchen",
    subcategories: ["Furniture", "Appliances", "Decor"],
  },
];

function BottomHeader({ isVisible }: BottomHeaderProps) {
  const locale = useLocale();
  const [isClick, setIsClick] = useState(false);
  const t = useTranslations();
  const pathname = usePathname();
  const dispatch = useDispatch();
  const { idToken } = useSelector((state: { Auth: any }) => state.Auth);
  const toggleNavbar = () => {
    setIsClick(!isClick);
  };
  const [isOpen, setIsOpen] = useState(false);
  const [openSubmenu, setOpenSubmenu] = useState<string | null>(null);
  const [subCategories, setSubcategories] = useState<any>([]);

  // useEffect(() => {
  //   const fetchSubCategoriesData = async () => {
  //     try {
  //       const response = await axios.get("/categories");
  //       const data = response?.data?.data;
  //       console.log("categories", data);
  //       setSubcategories([...data]);
  //     } catch (err: any) {
  //       console.error(err?.data?.message);
  //     }
  //   };
  //   fetchSubCategoriesData();
  // }, []);

  // useEffect(() => {
  //   const fetchSubCategoriesData = async () => {
  //     try {
  //       const response = await axios.get("/sub-categories");
  //       const data = response?.data?.data;
  //       console.log("sub categories", data);
  //       setSubcategories([...data]);
  //     } catch (err: any) {
  //       console.error(err?.data?.message);
  //     }
  //   };
  //   fetchSubCategoriesData();
  // }, []);

  return (
    // <nav className="bg-white py-2">
    <>
      <div
        className={`relative z-[999] flex items-center justify-between gap-4`}
      >
        <Link href={`/${locale}/`} locale={false}>
          <div className="aspect-[2/1] relative">
            {isVisible ? (
              <Image
                src={"/images/Logo.webp"}
                alt="Logo"
                width={96}
                height={79}
                style={{ objectFit: "contain" }}
                priority
              />
            ) : (
              <Image
                src={"/images/LogoWhite.webp"}
                alt="Logo"
                width={96}
                height={79}
                style={{ objectFit: "contain" }}
                priority
              />
            )}
          </div>
        </Link>
        <ul className=" hidden md:flex item-center justify-between gap-3 text-[18px] font-semibold">
          <li
            key={1}
            className={`${
              pathname.split("/").length === 2
                ? isVisible
                  ? "text-primary" // Active page + visible = text-white
                  : "text-[#fbc140]" // Active page + not visible = text-primary
                : isVisible
                ? "" // Non-active pages, when visible = text-primary
                : "text-white" // Non-active pages, when not visible = text-white
            } hover:${isVisible ? "" : "text-white"}`}
          >
            <Link
              href={`/${locale}/`}
              locale={false}
              prefetch={true}
              onClick={() => dispatch(fetchSearchValue(""))}
            >
              {t("home")}
            </Link>
          </li>
          <li
            key={2}
            className={`${
              pathname.split("/")[2] === "products"
                ? isVisible
                  ? "text-primary" // Active page + visible = text-primary
                  : "text-[#fbc140]" // Active page + not visible = text-[#fbc140]
                : isVisible
                ? "" // Non-active pages, when visible = text-primary
                : "text-white" // Non-active pages, when not visible = text-white
            } hover:${isVisible ? "" : "text-white"}`}
          >
            {/* <Link href={`/${locale}/products`} locale={false}>products</Link> */}
            <Link
              href={`/${locale}/products`}
              locale={false}
              prefetch={true}
              onClick={() => {
                dispatch(fetchSearchValue(""));
                if (pathname.split("/")[2] === "products") {
                  window.dispatchEvent(new Event("resetProductFilters"));
                }
              }}
            >
              {t("products")}
            </Link>
          </li>
          {/* <li key={3} className={`${pathname.split('/')[2]==="order"&&"text-primary"} hover:text-primary`}>
            <Link href={"/orders"} prefetch={true} onClick={()=>dispatch(fetchSearchValue(''))}>{t("orders")}</Link>
          </li> */}
          <li
            key={4}
            className={`${
              pathname.split("/")[2] === "offers"
                ? isVisible
                  ? "text-primary" // Active page + visible = text-primary
                  : "text-[#fbc140]" // Active page + not visible = text-[#fbc140]
                : isVisible
                ? "" // Non-active pages, when visible = text-primary
                : "text-white" // Non-active pages, when not visible = text-white
            } hover:${isVisible ? "" : "text-white"}`}
          >
            <Link
              href={`/${locale}/offers`}
              locale={false}
              prefetch={true}
              onClick={() => dispatch(fetchSearchValue(""))}
            >
              {t("offers")}
            </Link>
          </li>
          <li
            key={5}
            className={`${
              pathname.split("/")[2] === "about"
                ? isVisible
                  ? "text-primary" // Active page + visible = text-primary
                  : "text-[#fbc140]" // Active page + not visible = text-[#fbc140]
                : isVisible
                ? "" // Non-active pages, when visible = text-primary
                : "text-white" // Non-active pages, when not visible = text-white
            } hover:${isVisible ? "" : "text-white"}`}
          >
            <Link
              href={`/${locale}/about`}
              locale={false}
              prefetch={true}
              onClick={() => dispatch(fetchSearchValue(""))}
            >
              {t("about-us")}
            </Link>
          </li>
          {/* <li
            key={6}
            className={`${
              pathname.split("/")[2] === "category"
                ? isVisible
                  ? "text-primary" // Active page + visible = text-primary
                  : "text-[#fbc140]" // Active page + not visible = text-[#fbc140]
                : isVisible
                ? "" // Non-active pages, when visible = text-primary
                : "text-white" // Non-active pages, when not visible = text-white
            } hover:${isVisible ? "" : "text-white"}`}
          >
            <div className="relative">
              
              <button
                onMouseEnter={() => setIsOpen(true)}
                className="flex items-center gap-2"
              >
                Categories
                <ChevronDown
                  className={`transition ${isOpen ? "rotate-180" : ""}`}
                />
              </button>

              
              {isOpen && (
                <div
                  onMouseEnter={() => setIsOpen(true)}
                  onMouseLeave={() => {
                    setIsOpen(false);
                    setOpenSubmenu(null);
                  }}
                  className="absolute top-[25px] left-0 mt-2 w-56 bg-white shadow-lg rounded-lg border border-gray-200"
                >
                  {categories.map((category) => (
                    <div key={category.name} className="relative group">
                      <button
                        className="flex justify-between w-full px-4 py-2 text-gray-800 hover:bg-gray-100"
                        onMouseEnter={() => setOpenSubmenu(category.name)}
                      >
                        {category.name}
                        {category.subcategories.length > 0 && <ChevronRight />}
                      </button>

                      
                      {openSubmenu === category.name && (
                        <div className="absolute left-full top-0 mt-0 w-40 bg-white shadow-lg border border-gray-200 rounded-lg">
                          {category.subcategories.map((sub) => (
                            // href={`/product/${sub.toLowerCase()}`}
                            <a
                              key={sub}
                              href={`/product`}
                              className="block px-4 py-2 text-gray-700 hover:bg-gray-100"
                            >
                              {sub}
                            </a>
                          ))}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          </li> */}
        </ul>
        {idToken ? (
          <Button
            className={`font-semibold rtl:!text-[14px] text-[18px] md:!min-h-[40px] !bg-primary !border-primary text-white !outline-none px-8 ${
              isVisible ? "!text-white" : "!text-[#000] !bg-white !border-white"
            }`}
            onClick={() => {
              const section = document.getElementById("contactUs");
              if (section) {
                section.scrollIntoView({ behavior: "smooth" });
              }
            }}
            // onClick={()=>redirect('/login')}
            // className=" capitalize text-white bg-[#03B89E]  font-semibold rounded-[10px] hidden md:block  border hover:border-[#03B89E] hover:text-[#03B89E] hover:bg-[#fff] transition-colors duration-300 text-base md:text-lg"
          >
            {t("contact-us")}
          </Button>
        ) : (
          <Button
            className={`relative !bg-primary text-[18px] rtl:!text-[13px]  font-semibold !border-primary !min-w-[100px] md:!min-h-[40px] !outline-none !text-white px-8 ${
              isVisible ? "!text-white" : "!text-[#000] !bg-white !border-white"
            }`}
            //onClick={() => redirect("/login")}
            // className=" capitalize text-white bg-[#03B89E]  font-semibold rounded-[10px] hidden md:block  border hover:border-[#03B89E] hover:text-[#03B89E] hover:bg-[#fff] transition-colors duration-300 text-base md:text-lg"
          >
            <Link
              href={`/${locale}/login`}
              locale={false}
              className="absolute w-full h-full top-0 left-0 flex justify-center items-center rtl:!text-[13px]"
            >
              {t("log-in")}
            </Link>
          </Button>
        )}
        <div className="md:hidden flex items-center">
          <button
            className={`transition-all duration-300 ease-in-out inline-flex items-center justify-center p-2 rounded-md text-[#03B89E] focus:outline-none border border-[#03B89E] focus:bg-[#03B89E] focus:text-[#fff]  ${
              isVisible
                ? "text-[#03B89E] border-[#03B89E]"
                : "text-white border-white"
            }`}
            onClick={toggleNavbar}
          >
            {isClick ? (
              <svg
                className="h-6 w-6"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            ) : (
              <svg
                className="h-6 w-6"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M4 6h16M4 12h16m-7 6h7"
                />
              </svg>
            )}
          </button>
        </div>
      </div>
      {/* {isClick && (
        
      )} */}
      <div
        className={`transition-[max-height] duration-300 ease-in-out overflow-hidden relative z-[999] md:hidden mt-[15px] ${
          isClick ? "max-h-[177px]" : "max-h-0"
        }`}
      >
        <ul
          className={`flex flex-col bg-[##F0F0F0] py-[20px] px-[15px] gap-[5px] rounded-[10px] border  mb-2 ${
            isVisible ? "border-[#03B89E]" : "!text-white !border-white"
          }`}
        >
          <li key={1} className="!mb-1">
            <Link
              href={`/${locale}/`}
              locale={false}
              prefetch={true}
              onClick={toggleNavbar}
            >
              {t("home")}
            </Link>
          </li>
          <li key={2} className="!mb-1">
            {/* <Link href={`/${locale}/products`} locale={false}>products</Link> */}
            <Link
              href={`/${locale}/products`}
              locale={false}
              prefetch={true}
              onClick={() => {
                toggleNavbar();
                if (pathname.split("/")[2] === "products") {
                  window.dispatchEvent(new Event("resetProductFilters"));
                }
              }}
            >
              {t("products")}
            </Link>
          </li>
          <li key={3} className="!mb-1">
            <Link
              href={`/${locale}/offers`}
              locale={false}
              prefetch={true}
              onClick={toggleNavbar}
            >
              {t("offers")}
            </Link>
          </li>
          <li key={4} className="!mb-1">
            <Link
              href={`/${locale}/about`}
              locale={false}
              prefetch={true}
              onClick={toggleNavbar}
            >
              {t("about-us")}
            </Link>
          </li>
          {/* <li>
              {idToken ? (
                <Button
                  className="!bg-primary font-semibold !border-primary !outline-none !text-white px-8"
                  onClick={() => {
                    const section = document.getElementById("contactUs");
                    if (section) {
                      section.scrollIntoView({ behavior: "smooth" });
                    }
                  }}
                  // onClick={()=>redirect('/login')}
                  // className=" capitalize text-white bg-[#03B89E]  font-semibold rounded-[10px] hidden md:block  border hover:border-[#03B89E] hover:text-[#03B89E] hover:bg-[#fff] transition-colors duration-300 text-base md:text-lg"
                >
                  {t("contact-us")}
                </Button>
              ) : (
                <Button
                  className="!bg-primary font-semibold !border-primary !outline-none !text-white px-8"
                  onClick={() => redirect("/login")}
                  // className=" capitalize text-white bg-[#03B89E]  font-semibold rounded-[10px] hidden md:block  border hover:border-[#03B89E] hover:text-[#03B89E] hover:bg-[#fff] transition-colors duration-300 text-base md:text-lg"
                >
                  {t("log-in")}
                </Button>
              )}
            </li> */}
        </ul>
      </div>
      {/**</nav>** */}
    </>
  );
}

export default BottomHeader;
