import React, {useEffect, useRef, useState} from 'react'
import Link from 'next/link'
import { mdiChevronUp, mdiChevronDown, mdiBellOutline, mdiStoreOutline } from '@mdi/js'
import BaseDivider from './BaseDivider'
import BaseIcon from './BaseIcon'
import UserAvatarCurrentUser from './UserAvatarCurrentUser'
import NavBarMenuList from './NavBarMenuList'
import { useAppDispatch, useAppSelector } from '../stores/hooks'
import { MenuNavBarItem } from '../interfaces'
import { setDarkMode } from '../stores/styleSlice'
import { logoutUser } from '../stores/authSlice'
import { useRouter } from 'next/router';
import ClickOutside from "./ClickOutside";

type Props = {
  item: MenuNavBarItem
}

export default function NavBarItem({ item }: Props) {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const excludedRef = useRef(null);

  const navBarItemLabelActiveColorStyle = useAppSelector(
    (state) => state.style.navBarItemLabelActiveColorStyle
  )
  const navBarItemLabelStyle = useAppSelector((state) => state.style.navBarItemLabelStyle)
  const navBarItemLabelHoverStyle = useAppSelector((state) => state.style.navBarItemLabelHoverStyle)

  const currentUser = useAppSelector((state) => state.auth.currentUser);

  const userName = `${currentUser?.firstName ? currentUser?.firstName : ""} ${currentUser?.lastName ? currentUser?.lastName : ""}`;
  const merchantName = currentUser?.organization?.name || 'HD Stationary and Computer Accessor';
  const roleName = currentUser?.app_role?.name || 'Merchant';

  const [isDropdownActive, setIsDropdownActive] = useState(false)

  useEffect(() => {
    return () => setIsDropdownActive(false);
  }, [router.pathname]);

  const isActive = item.href && (router.pathname === item.href || (item.href !== '/' && router.pathname.startsWith(item.href)));

  const componentClass = [
    'block lg:flex items-center relative cursor-pointer transition-colors',
    isDropdownActive || isActive
      ? `${navBarItemLabelActiveColorStyle} dark:text-slate-400`
      : `${navBarItemLabelStyle} dark:text-white dark:hover:text-slate-400 ${navBarItemLabelHoverStyle}`,
    item.menu ? 'lg:py-2 lg:px-3' : 'py-2 px-3',
    item.isDesktopNoLabel ? 'lg:w-16 lg:justify-center' : '',
  ].join(' ')

  const itemLabel = item.isCurrentUser ? userName : item.label

  const handleMenuClick = () => {
    if (item.menu) {
      setIsDropdownActive(!isDropdownActive)
    }

    if (item.isToggleLightDark) {
      dispatch(setDarkMode(null))
    }

    if(item.isLogout) {
      dispatch(logoutUser())
      router.push('/login')
    }
  }

    const getItemId = (label) => {
    switch (label) {
      case 'Light/Dark':
        return 'themeToggle';
      case 'Log out':
        return 'logout';
      default:
        return undefined;
    }
  };

  if (item.isCurrentUser) {
    return (
      <div className="flex items-center space-x-2 lg:space-x-4 ml-2 lg:ml-6 border-l border-gray-100 dark:border-dark-700 pl-4 lg:pl-8 py-2">
         {/* Merchant Switcher Placeholder */}
         <div className="hidden md:flex items-center bg-white dark:bg-dark-900 border border-gray-200 dark:border-dark-700 rounded-xl px-3 py-1.5 shadow-sm cursor-pointer hover:border-indigo-300 transition-colors group">
            <div className="w-8 h-8 bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 rounded-lg flex items-center justify-center mr-2.5">
               <BaseIcon path={mdiStoreOutline} size={18} />
            </div>
            <div className="flex flex-col mr-6">
               <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider leading-none mb-0.5">Merchant</span>
               <span className="text-xs font-bold text-slate-700 dark:text-white leading-none truncate max-w-[150px]">{merchantName}</span>
            </div>
            <BaseIcon path={mdiChevronDown} size={18} className="text-slate-400 group-hover:text-indigo-500 transition-colors" />
         </div>

         {/* Notifications */}
         <div className="relative cursor-pointer group p-2 hover:bg-gray-50 dark:hover:bg-dark-900 rounded-xl transition-colors">
            <BaseIcon path={mdiBellOutline} size={24} className="text-slate-500 group-hover:text-indigo-600 transition-colors" />
            <span className="absolute top-2 right-2 w-2 h-2 bg-rose-500 rounded-full border-2 border-white dark:border-dark-800"></span>
         </div>

         {/* User Profile */}
         <div className="flex items-center cursor-pointer group pl-2" onClick={handleMenuClick} ref={excludedRef}>
            <div className="flex flex-col items-end mr-3 hidden sm:flex">
               <span className="text-xs font-black text-slate-800 dark:text-white leading-none mb-1">{userName}</span>
               <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest leading-none">{roleName}</span>
            </div>
            <div className="relative">
              <UserAvatarCurrentUser className="w-10 h-10 shadow-md border-2 border-indigo-100 dark:border-dark-700 rounded-full transition-transform group-hover:scale-105" />
              <div className="absolute -bottom-1 -right-1 w-4 h-4 bg-indigo-600 rounded-full border-2 border-white dark:border-dark-800 flex items-center justify-center">
                 <span className="text-[8px] text-white font-black uppercase">GU</span>
              </div>
            </div>
            
            {item.menu && (
              <div
                className={`${
                  !isDropdownActive ? 'lg:hidden' : ''
                } text-sm border-b border-gray-100 lg:border lg:bg-white lg:absolute lg:top-full lg:right-0 lg:min-w-[200px] lg:z-50 lg:rounded-2xl lg:shadow-xl lg:dark:bg-dark-900 dark:border-dark-700 mt-2`}
              >
                <ClickOutside onClickOutside={() => setIsDropdownActive(false)} excludedElements={[excludedRef]}>
                  <NavBarMenuList menu={item.menu} />
                </ClickOutside>
              </div>
            )}
         </div>
      </div>
    );
  }

  const NavBarItemComponentContents = (
    <>
      <div
        id={getItemId(itemLabel)}
        className={`flex items-center ${
          item.menu
            ? 'bg-gray-100 dark:bg-dark-800 lg:bg-transparent lg:dark:bg-transparent p-3 lg:p-0'
            : 'w-full'
        }`}
        onClick={handleMenuClick}
      >
        {item.icon && <BaseIcon path={item.icon} size={22} className={`transition-colors ${isActive ? 'text-indigo-600' : ''}`} />}
        <span
          className={`px-2 transition-colors grow ${
            item.isDesktopNoLabel && item.icon ? 'lg:hidden' : ''
          }`}
        >
          {itemLabel}
        </span>
        {item.menu && (
          <BaseIcon
            path={isDropdownActive ? mdiChevronUp : mdiChevronDown}
            className="hidden lg:inline-flex transition-colors"
          />
        )}
      </div>
      {item.menu && !item.isCurrentUser && (
        <div
          className={`${
            !isDropdownActive ? 'lg:hidden' : ''
          } text-sm border-b border-gray-100 lg:border lg:bg-white lg:absolute lg:top-full lg:left-0 lg:min-w-full lg:z-20 lg:rounded-lg lg:shadow-lg lg:dark:bg-dark-900 dark:border-dark-700`}
        >
          <ClickOutside onClickOutside={() => setIsDropdownActive(false)} excludedElements={[excludedRef]}>
            <NavBarMenuList menu={item.menu} />
          </ClickOutside>
        </div>
      )}
    </>
  )

  if (item.isDivider) {
    return <BaseDivider navBar />
  }

  if (item.href) {
    return (
      <Link href={item.href} target={item.target} className={componentClass}>
        {NavBarItemComponentContents}
      </Link>
    )
  }

  return <div className={componentClass} ref={excludedRef}>{NavBarItemComponentContents}</div>
}