"use client";
import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { ToggleSection } from "@/app/components/common/ToggleSection";
import Logo from "@/app/components/common/Logo";
import Cookies from "js-cookie";
import { useSelector } from "react-redux";
import SideBarNav from "@/app/components/common/sidebarNav";
import MiniCart from "@/app/components/common/mini-cart";
import HeaderSearchBox from "@/app/components/common/header-search-box";
import HeaderUserMenu from "@/app/components/common/HeaderUserMenu";


interface RootState {
  cart: {
    cartItemCount: number;
  };
}

export default function NavBar() {
  const pathname = usePathname();
  const [countBadge, setCountBadge] = useState(0);
  const token = Cookies.get("token");
  const bagItemCount = useSelector((state: RootState) => state.cart.cartItemCount);

  useEffect(() => {
    setCountBadge(bagItemCount);
  }, [bagItemCount]);

  useEffect(() => {
    if (token) {
      getProductList();
    }
  }, [token]);

  async function getProductList() {
    try {
      const response = await fetch(`/api/cart/list`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include", // Include cookies for authentication
      });

      if (!response.ok) {
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      }

      const data = await response.json();
      setCountBadge(data.data.length);
      return data;
    } catch (error) {
      console.error("Error fetching cart list:", error);
    }
  }

useEffect(() => {
    const closeAll = () => window.dispatchEvent(new Event("close-all-toggles"));
    closeAll();
  }, [pathname]);

  return (
    <header className="trasition fixed z-99 w-full bg-white/40 backdrop-blur-xl backdrop-filter duration-500 ease-in-out">
      <div className="wrapper relative py-1 md:py-0">
        <nav aria-label="Top">
          <div className="flex h-12 w-full flex-row items-center justify-between gap-4 align-middle">
            <div className="header-top-nav-list w-30">
              <ToggleSection
                id="site_menu_pop"
                showText={true}
                showBadge={false}
                countBadge={0}
                buttonText="Menu"
                iconName="icon-[ci--hamburger-md]"
              >
                <div className="fixed top-12 left-0 z-10 flex h-lvh w-full overflow-x-hidden overflow-y-auto bg-linear-to-t from-white/94 to-gray-100/94 shadow-2xl shadow-gray-950/10 backdrop-blur-md md:h-auto">
                  <div className="mob-noise absolute top-0 left-0 h-full w-full opacity-80"></div>
                  <SideBarNav />
                </div>
              </ToggleSection>
            </div>
            <div className="header-top-logo w-30">
              <Logo clickable={pathname !== "/"} />
            </div>
            <div className="header-top-right-nav w-30">
              <div className="flex flex-row justify-end">
                <ToggleSection
                  id="search_bar_pop"
                  showText={false}
                  showBadge={false}
                  countBadge={0}
                  buttonText="Site Search"
                  iconName="icon-[iconamoon--search]"
                >
                  {({ onClose }) => (
                    <div className="fixed top-12 left-0 z-10 flex w-full bg-white transition data-closed:translate-y-1 data-closed:opacity-0 data-enter:duration-200 data-enter:ease-out data-leave:duration-150 data-leave:ease-in">
                      <div className="flex w-full flex-col justify-center">
                        <HeaderSearchBox onClose={onClose} />
                      </div>
                    </div>
                  )}
                </ToggleSection>
                <ToggleSection
                  id="mini_bag_pop"
                  showText={false}
                  showBadge={true}
                  countBadge={countBadge}
                  buttonText="Shopping Bag"
                  iconName="icon-[hugeicons--shopping-bag-02]"
                >
                  <div className="fixed top-11 right-0 left-0 z-10 mt-0 flex w-screen bg-white transition md:absolute md:left-auto md:w-90">
                    <div className="flex w-full flex-col p-5 md:px-10">
                      <MiniCart />
                    </div>
                  </div>
                </ToggleSection>
                <ToggleSection
                  id="user_menu_pop"
                  showText={false}
                  showBadge={false}
                  countBadge={0}
                  buttonText="User Menu"
                  iconName="icon-[hugeicons--user]"
                >
                  <div className="fixed top-11 right-0 left-0 z-10 mt-0 flex w-screen bg-white transition md:absolute md:left-auto md:w-90">
                    <div className="flex w-full flex-col p-5 md:px-10 border-1 border-gray-950">
                      <HeaderUserMenu />
                    </div>
                  </div>
                </ToggleSection>
              </div>
            </div>
          </div>
        </nav>
      </div>
    </header>
  );
}
