"use client";
import "./navbar.css";
import React, { useState, useRef, useEffect } from "react";
import { logout, getUserInfo } from "@/app/utils/token";
import { useRouter } from "next/navigation";
import { useAppSelector, useAppDispatch } from "@/app/hooks/useDispatch";
import { toggleSidebar } from "@/app/redux/features/auth/authAction";
const Navbar = () => {
  const { isSidebarOpen } = useAppSelector((state) => state.auth);
  const dispatch = useAppDispatch();

  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const sidebarButtonRef = useRef<HTMLImageElement>(null);
  const router = useRouter();
  const userInfo = getUserInfo();
  const userName =
    userInfo?.name || userInfo?.username || userInfo?.email || "U";
  const firstLetter = userName.charAt(0).toUpperCase();
  const userPhoto = userInfo?.photo
    ? `https://admin.eventx.fr/uploads/users/${userInfo.photo}`
    : null;
  const toggleSidebarButton = (): void => {
    dispatch(toggleSidebar());
  };
  const handleLogout = () => {
    logout();
    router.push("/login");
    setIsDropdownOpen(false);
  };

  const handleProfile = () => {
    setIsDropdownOpen(false);
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsDropdownOpen(false);
      }
      if (
        isSidebarOpen &&
        sidebarButtonRef.current &&
        !sidebarButtonRef.current.contains(event.target as Node)
      ) {
        dispatch(toggleSidebar());
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isSidebarOpen, dispatch]);

  return (
    <>
      <div className="flex items-start justify-between">
        <img className="w-16" src="/logo.svg" alt="" />
        <div className="flex items-center gap-4 relative" ref={dropdownRef}>
          <div className="flex items-center gap-2 cursor-pointer">
            {/* name */}
            <p
              style={{ fontSize: "1.1rem" }}
              className="quaternary-heading"
              onClick={() => setIsDropdownOpen(!isDropdownOpen)}
            >
              {userInfo?.name}
            </p>
            {/* zaak-profile */}
            {userPhoto ? (
              <img
                src={userPhoto}
                alt={`${userName}'s profile`}
                onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                className="w-10 h-10 rounded-full object-cover border-2 border-gray-200"
                onError={(e) => {
                  e.currentTarget.style.display = "none";
                }}
              />
            ) : (
              <div
                onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                className="w-10 h-10 bg-[#0071bc] rounded-full flex items-center justify-center text-white font-semibold text-lg"
              >
                {firstLetter}
              </div>
            )}
            <div className="lg-set:hidden text-4xl" ref={sidebarButtonRef}>
              <div
                className={`nav_div cd-primary-nav-trigger ${
                  isSidebarOpen ? "is-clicked" : ""
                }`}
                onClick={toggleSidebarButton}
                style={{ cursor: "pointer" }}
              >
                <div className="cd-menu-icon"></div>
              </div>
            </div>
          </div>

          {/* Dropdown Menu */}
          {isDropdownOpen && (
            <div className="absolute top-full right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-50 border border-gray-200">
              <button
                onClick={handleProfile}
                className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors duration-150"
              >
                Profil
              </button>
              <button
                onClick={handleLogout}
                className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors duration-150"
              >
                Se déconnecter
                {/* Logout */}
              </button>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export default Navbar;
