"use client";
import { useState, useRef, useEffect } from "react";
import {
  IoNotifications,
  IoEye,
  IoCart,
  IoShieldCheckmark,
  IoMenu,
  IoSearch,
  IoPerson,
  IoLogOut,
  IoChevronDown,
  IoHeart,
} from "react-icons/io5";
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 { RootState } from "@/redux/store";
import { useSelector } from "react-redux";
import Cookies from "js-cookie";
import SearchComponent from "@/components/searchComponent";

interface Notification {
  id: number;
  avatar: string;
  message: string;
  time: string;
}

interface User {
  profile?: {
    full_name?: string;
  };
  email?: string;
  picUrl?: string;
}

export default function AdminHeader() {
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const sidebarRef = useRef<HTMLDivElement>(null);
  const profileRef = useRef<HTMLDivElement>(null);
  const notificationRef = useRef<HTMLDivElement>(null);


  const router = useRouter();
  const pathname = usePathname();
  const { data: session } = useSession();

  const cartCounts = useSelector(
    (state: RootState) => state.cart.totalQuantity
  );


  const cart = useSelector((state: RootState) => state.cart);
  const wishlistCounts = useSelector((state: RootState) => state.wishlist.WishListItem.length)

  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 handleNotificationBlur = (event: React.FocusEvent) => {
    const relatedTarget = event.relatedTarget as Node | null;
    if (!notificationRef.current?.contains(relatedTarget)) {
      setShowNotifications(false);
    }
  };

  const handleProfileBlur = (event: React.FocusEvent) => {
    const relatedTarget = event.relatedTarget as Node | null;
    if (!profileRef.current?.contains(relatedTarget)) {
      setShowProfileMenu(false);
    }
  };

  const handleBlur = (event: React.FocusEvent) => {
    const relatedTarget = event.relatedTarget as Node | null;
    if (!sidebarRef.current?.contains(relatedTarget)) {
      setIsSidebarOpen(false);
    }
  };

  useEffect(() => {
    setIsMounted(true);
    return () => {
      // Cleanup function
      setIsMounted(false);
    };
  }, []);

  // Fetch user data
  useEffect(() => {
    if (!session?.user?.uuid) return;

    let isMounted = 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 (isMounted) {
          setUser(data.User);

        }
      } catch (error: any) {
        if (error.name !== "AbortError") {
          console.error("Error:", error);
          if (isMounted) setPicUrl("/profile/user.png");
        }
      } finally {
        if (isMounted) setIsLoading(false);
      }
    };

    fetchUser();

    return () => {
      isMounted = false;
    };
  }, [session])

  const handleLogout = async () => {
    try {
      await signOut({ redirect: false });
      Cookies.remove("picUrl")
      router.replace("/");
    } catch (err) {
      console.error("Error:", err);
    }
  };

  const toggleProfileMenu = () => {
    setShowProfileMenu(!showProfileMenu);
    if (showNotifications) setShowNotifications(false);
  };

  const toggleNotifications = () => {
    setShowNotifications(!showNotifications);
    if (showProfileMenu) setShowProfileMenu(false);
  };

  const notifications: Notification[] = [
    {
      id: 1,
      avatar: "/order/order.png",
      message: "Hey, what's up? All set for the presentation?",
      time: "a few moments ago",
    },
    {
      id: 2,
      avatar: "/order/tracking.png",
      message: "and 5 others started following you.",
      time: "10 minutes ago",
    },
    {
      id: 3,
      avatar: "/order/package.png",
      message: "and 141 others love your story. See it and view more stories.",
      time: "44 minutes ago",
    },
    {
      id: 4,
      avatar: "/order/order-delivery.png",
      message:
        "posted a new video: How to implement design trends - learn how to implement the new design trend.",
      time: "3 hours ago",
    },
  ];

  return (
    <>
      {/* Overlay */}
      {isSidebarOpen && (
        <div
          className="fixed inset-0 bg-black opacity-50 z-40 md:hidden"
          onClick={() => setIsSidebarOpen(false)}
        ></div>
      )}

      {/* 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)}
              aria-controls="drawer-navigation"
              data-drawer-toggle
              className="p-2 mr-2 text-white rounded-lg cursor-pointer md:hidden hover:bg-secondary focus:bg-gray-100 focus:ring-2 focus:ring-gray-100"
            >
              <IoMenu className="w-6 h-6" />
              <span className="sr-only">Toggle sidebar</span>
            </button>

            {/* logo */}
            <Link href="/" className="flex items-center justify-between mr-4">
              <span className="self-center text-2xl font-semibold whitespace-nowrap text-white focus:border-secondary">
                Barrack
              </span>
            </Link>


            {/* Search component here */}
            <SearchComponent />
            {/* Search component here */}
          </div>

          <div className="flex items-center lg:order-2">
            {/* cart 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>
                {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">
                    {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>

            {session ? (
              <div className="flex">
                <div>
                  {/* notification button */}
                  {/* <button
                    type="button"
                    data-dropdown-toggle="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}
                      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>
                  {/* profile button */}
                  <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="false"
                    data-dropdown-toggle="dropdown"
                    onClick={toggleProfileMenu}
                    onBlur={handleProfileBlur}
                  >
                    <span className="sr-only">Open user menu</span>
                    <Image
                      height={28}
                      width={28}
                      className="w-8 h-8 rounded-full"
                      src={picUrl}
                      alt="user photo"
                      onError={() => setPicUrl("/profile/user.png")}
                    />
                  </button>

                  {isMounted && showProfileMenu && (
                    <div
                      ref={profileRef}
                      tabIndex={0}
                      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 || <IoPerson className="h-4 w-4" />}
                            {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"
                        >
                          <IoLogOut className="h-4 w-4" />
                          {profileOptions[profileOptions.length - 1].title}
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            ) : (
              <div className="flex items-center space-x-4">
                <button
                  onClick={() => router.push("/login")}
                  className="relative p-2 mr-1 text-white rounded-lg hover:bg-blue-700"
                >
                  <IoCart className="h-5 w-5" />
                </button>
                <button
                  className="bg-white text-blue-600 hover:bg-blue-50 px-4 py-2 rounded"
                  onClick={() => router.push("/login")}
                >
                  Login
                </button>
              </div>
            )}
          </div>
        </div>
      </nav>

      {/* Sidebar */}
      <aside
        ref={sidebarRef}
        onBlur={handleBlur}
        tabIndex={0}
        className={`fixed top-0 left-0 z-40 w-64 h-screen pt-14 transition-transform ${isSidebarOpen ? "translate-x-0" : "-translate-x-full"
          } bg-white border-r border-gray-200 md:translate-x-0`}
        aria-label="Sidenav"
        id="drawer-navigation"
      >
        <div className="overflow-y-auto py-5 px-3 h-full bg-white">
          {session && (
            <ul className="space-y-2">
              {adminNavLinks.map((link) => (
                <li key={link.key}>
                  <Link
                    href={link.path}
                    className={`flex items-center p-2 text-base font-medium text-gray-900 rounded-lg hover:bg-gray-200 group ${pathname.includes(link.key) ? "bg-gray-200" : ""
                      }`}
                  >
                    {link.icon} <span className="ml-3">{link.title}</span>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>
      </aside>
    </>
  );
}
