"use client";
import { useState, useRef, useEffect } from "react";
import {
  IoNotifications,
  IoEye,
  IoCart,
  IoShieldCheckmark,
  IoArrowBack,
  IoMenu,
  IoHeart,
  IoSearchOutline,
  IoExitOutline,
} from "react-icons/io5";
import { FaUserCircle } from "react-icons/fa";
import Image from "next/image";
import Link from "next/link";
import { useRouter, usePathname } from "next/navigation";
import { signOut, useSession } from "next-auth/react";
import { profileOptions, adminNavLinks } from "@/lib/constrants";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "@/redux/store";
import { fetchCartFromBackend } from "@/redux/slices/cartSlice";
import { fetchWishlistFromBackend } from "@/redux/slices/wishlistSlice";
import Cookies from "js-cookie";
import SearchComponent from "@/components/searchComponent";
// import {fetchWishlistFromBackend} from "@/redux/slices/wishlistSlice";

interface MenuItem {
  title: string;
  href?: string;
  subItems?: MenuItem[];
}

interface Notification {
  id: number;
  avatar: string;
  message: string;
  time: string;
}

interface User {
  profile?: {
    full_name?: string;
  };
  email?: string;
  picUrl?: string;
}



export default function Header() {
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [currentMenu, setCurrentMenu] = useState<MenuItem[]>([]);
  const [user, setUser] = useState<User | null>(null);
  const [picUrl, setPicUrl] = useState("/profile/user.png");
  const [isLoading, setIsLoading] = useState(false);
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  const [showNotifications, setShowNotifications] = useState(false);
  const [isMounted, setIsMounted] = useState(false);
  const [showMobileSearch, setShowMobileSearch] = useState(false)

  const sidebarRef = useRef<HTMLDivElement>(null);
  const profileRef = useRef<HTMLDivElement>(null);
  const notificationRef = useRef<HTMLDivElement>(null);
  const mobileSearchRef = useRef<HTMLDivElement>(null);


  const router = useRouter();


  const { data: session } = useSession();

  const [searchKey, setSearchKey] = useState("")

  const cartCounts = useSelector(
    (state: RootState) => state.cart.totalQuantity
  );


  // console.log(`Cart Counts: ${cartCounts}`)
  // const cart = useSelector((state: RootState) => state.cart);
  const wishlistCounts = useSelector((state: RootState) => state.wishlist.WishListItem.length)

  const dispatch = useDispatch<AppDispatch>();
  // const wishlist = useSelector((state: RootState) => state.wishlist)

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    router.push(`/search?q=${encodeURIComponent(searchKey)}`);
  };

  // Handle blur events
  const handleNotificationBlur = (event: React.FocusEvent) => {
    const relatedTarget = event.relatedTarget as HTMLElement;
    if (!notificationRef.current?.contains(relatedTarget)) {
      setShowNotifications(false);
    }
  };

  const handleProfileBlur = (event: React.FocusEvent) => {
    const relatedTarget = event.relatedTarget as HTMLElement;
    if (!profileRef.current?.contains(relatedTarget)) {
      setShowProfileMenu(false);
    }
  };

  const handleBlur = (event: React.FocusEvent) => {
    const relatedTarget = event.relatedTarget as HTMLElement;
    if (!sidebarRef.current?.contains(relatedTarget)) {
      setIsSidebarOpen(false);
    }
  };

  const getCurrentItem = (): MenuItem | null => {
    if (currentMenu.length === 0) return null;
    return currentMenu[currentMenu.length - 1];
  };

  // Mount state
  useEffect(() => {
    setIsMounted(true);
    // return () => setIsMounted(false);
  }, []);

  useEffect(() => {
    if (!session?.user?.uuid) return;
    dispatch(fetchCartFromBackend());
    dispatch(fetchWishlistFromBackend());
  }, [dispatch, session?.user?.uuid]);


  // Fetch user data
  useEffect(() => {
    if (!session?.user?.uuid) return;

    let Mounted = true

    const fetchUser = async () => {
      setIsLoading(true);
      try {


        const res = await fetch(`/api/user/${session.user.uuid}`)
        if (!res.ok) throw new Error("Failed to fetch user data")
        const data = await res.json();
        var userPicUrl = Cookies.get("picUrl")

        if (!userPicUrl) {
          const response = await fetch('/api/user/propic')

          const picData = await response.json()

          userPicUrl = picData.picUrl
          Cookies.set("picUrl", picData.picUrl, { expires: 1 })

        }
        setPicUrl(userPicUrl || "/profile/user.png")

        if (Mounted) {
          setUser(data.User);

        }
      } catch (error: any) {
        if (error.name !== "AbortError") {
          console.error("Error:", error);
          if (Mounted) setPicUrl("/profile/user.png");
        }
      } finally {
        if (Mounted) setIsLoading(false);
      }
    };

    fetchUser();


  }, [session])

  const handleLogout = async () => {
    try {
      // await fetch("/api/user/clear-cookies")

      await signOut({ redirect: false })
      Cookies.remove("picUrl")
      router.replace("/")

    } catch (err) {
      console.error("Error:", err);
    }
  }


  const toggleProfileMenu = () => {
    setShowProfileMenu((prev) => !prev);
    if (showNotifications) setShowNotifications(false);
  };

  const toggleNotifications = () => {
    setShowNotifications((prev) => !prev);
    if (showProfileMenu) setShowProfileMenu(false);
  };

  // Close menus when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        sidebarRef.current &&
        !sidebarRef.current.contains(event.target as Node)
      ) {
        setIsSidebarOpen(false);
      }

      if (
        profileRef.current &&
        !profileRef.current.contains(event.target as Node)
      ) {
        setShowProfileMenu(false);
      }

      if (
        notificationRef.current &&
        !notificationRef.current.contains(event.target as Node)
      ) {
        setShowNotifications(false);
      }

      // NEW: Close mobile search if click is outside
      if (
        mobileSearchRef.current &&
        !mobileSearchRef.current.contains(event.target as Node)
      ) {
        setShowMobileSearch(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const [isOpen, setIsOpen] = useState(false);
  const [menuStack, setMenuStack] = useState<CategoryType[]>([]);
  const [categories, setCategories] = useState<CategoryType[]>([]);
  const [currentCategoryType, setCurrentCategoryType] = useState("MAIN_CATEGORY");
  const [parentCategories, setParentCategories] = useState<CategoryType[]>([]);
  const [grandParentCategories, setGrandParentCategories] = useState<CategoryType[]>([]);

  const [highlightedCategories, setHighlightedCategories] = useState<CategoryType[]>([]);

  const fetchCategories = async () => {
    const res = await fetch("/api/categories", { cache: 'no-store' });

    if (res.status !== 200) {
      console.error("Failed to fetch categories", res.statusText);
      throw new Error("Failed to fetch all categories");
    }
    const data = await res.json();
    // console.log(data.data);
    setCategories(data.data);

    // console.log(data.data)

    setHighlightedCategories(data.data.slice(0, 5));
    setMenuStack(data.data);
  };

  useEffect(() => {
    fetchCategories();
  }, []);
  const toggleSidebar = () => {
    setIsOpen(!isOpen);
    setMenuStack(categories);
    setCurrentCategoryType("MAIN_CATEGORY");
  };

  const toggleMobileSearchBar = () => {

    setShowMobileSearch(!showMobileSearch)

  }

  const goToSubmenu = (item: CategoryType) => {
    if (item.children) {
      setGrandParentCategories(parentCategories);
      setParentCategories(menuStack);
      setMenuStack(item.children);

      setCurrentCategoryType(item.children[0]?.category_type);
    }
  };

  const goBack = () => {
    setMenuStack(parentCategories);
    setParentCategories(grandParentCategories);
    setCurrentCategoryType(parentCategories[0]?.category_type);
  };
  return (
    <>
      {/* Overlay */}
      {isSidebarOpen && (
        <div
          className="fixed inset-0 bg-black opacity-50 z-40 md:hidden"
          onClick={() => setIsSidebarOpen(false)}
          aria-hidden="true"
        />
      )}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 z-40"
          onClick={toggleSidebar}
        />
      )}
      {/* Navbar */}
      <nav className="bg-primary border-b border-gray-200 px-4 py-2.5 fixed left-0 right-0 top-0 z-50">
        <div className="flex flex-wrap justify-between items-center">
          <div className="flex justify-start items-center">
            <button
              // onClick={() => setIsSidebarOpen(!isSidebarOpen)}
              onClick={toggleSidebar}
              aria-controls="drawer-navigation"
              aria-expanded={isSidebarOpen}
              className="p-2 mr-2 hover:bg-secondary rounded-lg block [@media(min-width:1390px)]:hidden"
            >
              <IoMenu className="text-white size-6" />
              <span className="sr-only">Toggle sidebar</span>
            </button>

            <a href="/" className="flex items-center justify-between mr-4">
              <span className="self-center text-xl md:text-2xl font-semibold whitespace-nowrap text-white focus:border-secondary ">
                Barrack
              </span>
            </a>

            {/* Search Component here*/}
            <SearchComponent />
            {/* Search component here */}

          </div>
          <div className="flex items-center lg:order-2">
            {session ? (
              <div className="flex">
                <div>

                  <button onClick={toggleMobileSearchBar} className="text-white md:hidden font-bold hover:bg-secondary p-2 rounded-xl">
                    <IoSearchOutline size={27} />
                  </button>

                  <Link href="/cart" passHref>
                    <button
                      type="button"
                      className="relative inline-flex items-center p-2 text-sm font-medium text-center text-white rounded-lg hover:bg-secondary focus:ring-4 focus:outline-none focus:ring-blue-300"
                    >
                      <IoCart className="size-6" />
                      {/* <span className="sr-only">Cart</span> */}

                      <div className="absolute inline-flex items-center justify-center w-5 h-5 text-xs font-bold text-red-500 bg-white border-2 border-white rounded-full top-0 -end-1">
                        {isMounted && cartCounts}
                      </div>

                    </button>
                  </Link>



                  <Link href="/wishlist" passHref>
                    <button
                      type="button"
                      className="relative inline-flex items-center p-2 text-sm font-medium text-center text-white rounded-lg hover:bg-secondary focus:ring-4 focus:outline-none focus:ring-blue-300"
                    >
                      <IoHeart className="size-6" />
                      <span className="sr-only">Wishlist</span>
                      {isMounted && (
                        <div className="absolute inline-flex items-center justify-center w-5 h-5 text-xs font-bold text-red-500 bg-white border-2 border-white rounded-full top-0 -end-1">
                          {wishlistCounts}
                        </div>
                      )}
                    </button>
                  </Link>



                  {/* <button
                    type="button"
                    aria-expanded={showNotifications}
                    aria-controls="notification-dropdown"
                    className="p-2 mr-1 text-gray-500 rounded-lg hover:bg-secondary focus:ring-4 focus:ring-gray-300"
                    onClick={toggleNotifications}
                    onBlur={handleNotificationBlur}
                  >
                    <span className="sr-only">View notifications</span>
                    <IoNotifications className="text-white size-6" />
                  </button>

                  {isMounted && showNotifications && (
                    <div
                      ref={notificationRef}
                      onBlur={handleNotificationBlur}
                      tabIndex={0}
                      id="notification-dropdown"
                      className="absolute right-0 z-50 my-4 w-96 text-base list-none divide-y divide-gray-100 shadow rounded-xl bg-white"
                    >
                      <div className="block py-2 px-4 text-base font-medium text-center text-gray-700 bg-gray-50 rounded-t-xl">
                        Notifications
                      </div>
                      <div>
                        {notifications.map((notification) => (
                          <Link
                            key={notification.id}
                            href="#"
                            className="flex py-3 px-4 border-b hover:bg-gray-100"
                          >
                            <div className="flex-shrink-0">
                              <Image
                                className="w-7 h-7 rounded-full"
                                src={notification.avatar}
                                alt="Notification icon"
                                width={28}
                                height={28}
                              />
                            </div>
                            <div className="pl-3 w-full">
                              <div className="text-gray-500 font-normal text-sm mb-1.5">
                                {notification.message}
                              </div>
                              <div className="text-xs font-medium text-primary-600">
                                {notification.time}
                              </div>
                            </div>
                          </Link>
                        ))}
                      </div>
                      <Link
                        href="#"
                        className="block py-2 text-md font-medium text-center text-gray-900 bg-gray-50 hover:bg-gray-100 rounded-b-xl"
                      >
                        <div className="inline-flex items-center">
                          <IoEye />
                          <span className="ml-2">View all</span>
                        </div>
                      </Link>
                    </div>
                  )} */}
                </div>
                <div>
                  <button
                    type="button"
                    className="flex mx-3 text-sm rounded-full md:mr-0 focus:ring-4 focus:ring-gray-200 border-4 border-white"
                    id="user-menu-button"
                    aria-expanded={showProfileMenu}
                    aria-controls="user-menu"
                    onClick={toggleProfileMenu}
                    onBlur={handleProfileBlur}
                  >
                    <span className="sr-only">Open user menu</span>
                    <Image
                      height={32}
                      width={32}
                      className="w-8 h-8 rounded-full"
                      src={picUrl}
                      alt="User profile photo"
                      onError={() => setPicUrl("/profile/user.png")}
                    />
                  </button>
                  {isMounted && showProfileMenu && (
                    <div
                      ref={profileRef}
                      tabIndex={0}
                      id="user-menu"
                      onBlur={handleProfileBlur}
                      className="absolute right-0 z-10 mt-2 w-60 divide-y divide-gray-200 rounded-lg border border-gray-100 bg-white text-left text-sm shadow-lg"
                    >
                      <div className="py-3 px-4">
                        <div className="flex items-center gap-3">
                          <div className="relative h-10 w-10">
                            <Image
                              src={picUrl}
                              width={40}
                              height={40}
                              alt="User avatar"
                              className="w-full h-full rounded-full"
                              onError={() => setPicUrl("/profile/user.png")}
                            />
                          </div>
                          <div className="text-sm">
                            <div className="font-medium text-gray-700">
                              {user?.profile?.full_name?.split(" ")[0] ||
                                "User"}
                            </div>
                            <div className="text-[11px] text-gray-400">
                              {user?.email || ""}
                            </div>
                          </div>
                        </div>
                      </div>

                      {session?.user.role === "ADMIN" && (
                        <div className="p-1">
                          <Link
                            href="/admin/dashboard"
                            className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-gray-700 hover:bg-gray-100"
                          >
                            <IoShieldCheckmark className="h-4 w-4" />
                            <p>Dashboard</p>
                          </Link>
                        </div>
                      )}

                      <div className="p-1">
                        {profileOptions.slice(0, profileOptions.length - 1).map((option) => (
                          <Link
                            key={option.id}
                            href={option.url}
                            className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-gray-700 hover:bg-gray-100"
                          >
                            {option.icon ? (
                              option.icon
                            ) : (
                              <FaUserCircle />
                            )}
                            {option.title}
                          </Link>
                        ))}
                      </div>

                      <div className="p-1">
                        <button
                          onClick={handleLogout}
                          className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-gray-700 hover:bg-gray-100"
                        >
                          <IoExitOutline />
                          {profileOptions[4].title}
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            ) : (
              <div className="flex items-center space-x-4">

                <button onClick={toggleMobileSearchBar} className="text-white md:hidden font-bold hover:bg-secondary p-2 rounded-xl">
                  <IoSearchOutline size={27} />
                </button>

                <Link href="/cart" passHref>
                  <button
                    type="button"
                    className="relative inline-flex items-center p-2 text-sm font-medium text-center text-white rounded-lg hover:bg-secondary focus:ring-4 focus:outline-none focus:ring-blue-300"
                  >
                    <IoCart className="size-6" />
                    {/* <span className="sr-only">Cart</span> */}

                    <div className="absolute inline-flex items-center justify-center w-5 h-5 text-xs font-bold text-red-500 bg-white border-2 border-white rounded-full top-0 -end-1">
                      {isMounted && cartCounts}
                    </div>

                  </button>
                </Link>
                <button
                  className="text-primary bg-white hover:bg-secondary hover:text-white focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-2.5 py-2 me-2 mb-2 md:px-5 md:py-2.5 focus:outline-none"
                  onClick={() => router.push("/login")}
                >
                  Login
                </button>
              </div>
            )}
          </div>
        </div>
      </nav>

      {/* Mobile Search Bar */}
      {showMobileSearch && (
        <div ref={mobileSearchRef} className="fixed top-16 left-0 right-0 bg-primary p-4 z-50 md:hidden">
          <form action="#" method="GET" className="w-full" onSubmit={handleSearch}>
            <div className="relative w-full flex flex-row bg-white rounded-lg">
              <input
                type="text"
                id="mobile-topbar-search"
                className="text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block
                   w-[92%] pl-3 p-2.5 "
                placeholder="Search"
                onChange={(e) => setSearchKey(e.target.value)}
              />
              <button className="flex items-center justify-center w-[8%] font-semibold bg-cyan-400 rounded-r-lg">
                <IoSearchOutline />
              </button>
            </div>
          </form>
        </div>
      )}

      {/* new Sidebar */}
      <div
        className={`fixed top-0 left-0 h-full w-64 bg-white shadow-lg z-50 transition-transform 
          overflow-y-auto duration-300 ease-in-out
          ${isOpen ? "translate-x-0" : "-translate-x-full"
          }`}
      >
        <div className="p-4">
          {currentCategoryType != "MAIN_CATEGORY" && (
            <button
              onClick={goBack}
              className="flex items-center mb-4 text-blue-600"
            >
              <IoArrowBack className="mr-1" />
              Back
            </button>
          )}

          <h2 className="text-xl font-bold mb-4">
            {currentCategoryType === "MAIN_CATEGORY"
              ? "Shop Categories"
              : menuStack[menuStack.length - 1].name}
          </h2>
          <ul className="space-y-2">
            {menuStack?.map((item) => (
              <li key={item.name} className="flex justify-between items-center">
                <Link
                  onClick={() => setIsOpen(false)}
                  href={`/${item.name}`}
                  className="flex-1 p-2 hover:bg-gray-100 rounded text-left"
                >
                  {item.name}
                </Link>
                {item.children?.length > 0 && (
                  <button
                    onClick={() => goToSubmenu(item)}
                    className="p-2 text-gray-600 hover:text-gray-900"
                    aria-label={`Expand ${item.name}`}
                  >
                    →
                  </button>
                )}
              </li>
            ))}
          </ul>
        </div>
      </div>
    </>
  );
}
