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

type Props = {
  item: MenuNavBarItem;
};

export default function NavBarItem({ item }: Props) {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const excludedRef = useRef(null);
  const currentUser = useAppSelector((state) => state.auth.currentUser);
  const userName = `${currentUser?.firstName ? currentUser?.firstName : ''} ${
    currentUser?.lastName ? currentUser?.lastName : ''
  }`.trim();
  const [isDropdownActive, setIsDropdownActive] = useState(false);

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

  const componentClass = [
    'relative block cursor-pointer rounded-xl text-sm font-semibold text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-950 lg:flex lg:items-center lg:mx-1',
    item.menu ? 'lg:px-3 lg:py-2' : 'px-3 py-2',
    item.isDesktopNoLabel ? 'lg:w-10 lg:justify-center' : '',
  ].join(' ');

  const itemLabel = item.isCurrentUser
    ? userName || currentUser?.email || 'Account'
    : 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;
    }
  };

  const NavBarItemComponentContents = (
    <>
      <div
        id={getItemId(itemLabel)}
        className={`flex items-center ${
          item.menu ? 'bg-slate-50 p-3 lg:bg-transparent lg:p-0' : 'w-full'
        }`}
        onClick={handleMenuClick}
      >
        {item.icon && (
          <BaseIcon path={item.icon} size={20} className='transition-colors' />
        )}
        <span
          className={`px-2 transition-colors ${
            item.isDesktopNoLabel && item.icon ? 'lg:hidden' : ''
          }`}
        >
          {itemLabel}
        </span>
        {item.isCurrentUser && (
          <UserAvatarCurrentUser className='mr-2 inline-flex h-7 w-7' />
        )}
        {item.menu && (
          <BaseIcon
            path={isDropdownActive ? mdiChevronUp : mdiChevronDown}
            className='hidden transition-colors lg:inline-flex'
          />
        )}
      </div>
      {item.menu && (
        <div
          className={`${
            isDropdownActive ? 'block' : 'hidden'
          } border-b border-slate-100 text-sm lg:absolute lg:right-0 lg:top-[calc(100%+0.5rem)] lg:z-40 lg:w-56 lg:overflow-hidden lg:rounded-xl lg:border lg:border-slate-200 lg:bg-white lg:py-2 lg:shadow-xl dark:border-dark-700 dark:bg-dark-900`}
        >
          <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>
  );
}
