import React, { ReactNode, useEffect, useState } from 'react';
import { mdiClose, mdiDotsVertical } from '@mdi/js';
import { containerMaxW } from '../config';
import BaseIcon from './BaseIcon';
import NavBarItemPlain from './NavBarItemPlain';
import NavBarMenuList from './NavBarMenuList';
import { MenuNavBarItem } from '../interfaces';

type Props = {
  menu: MenuNavBarItem[];
  className: string;
  children: ReactNode;
};

export default function NavBar({ menu, className = '', children }: Props) {
  const [isMenuNavBarActive, setIsMenuNavBarActive] = useState(false);
  const [isScrolled, setIsScrolled] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 0);
    };

    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  const handleMenuNavBarToggleClick = () => {
    setIsMenuNavBarActive(!isMenuNavBarActive);
  };

  return (
    <nav
      className={`${className} fixed inset-x-0 top-0 z-30 h-16 w-screen bg-white/95 shadow-sm backdrop-blur transition-position lg:w-auto dark:bg-dark-800/95 ${
        isScrolled ? 'border-b border-slate-200' : 'border-b border-transparent'
      }`}
    >
      <div className={`flex h-16 lg:items-stretch ${containerMaxW}`}>
        <div className='flex h-16 flex-1 items-center'>{children}</div>
        <div className='flex h-16 flex-none items-stretch lg:hidden'>
          <NavBarItemPlain onClick={handleMenuNavBarToggleClick}>
            <BaseIcon
              path={isMenuNavBarActive ? mdiClose : mdiDotsVertical}
              size='24'
            />
          </NavBarItemPlain>
        </div>
        <div
          className={`${
            isMenuNavBarActive ? 'block' : 'hidden'
          } absolute left-0 top-16 max-h-screen-menu w-screen overflow-y-auto border-b border-slate-200 bg-white shadow-lg lg:static lg:flex lg:w-auto lg:items-center lg:overflow-visible lg:border-b-0 lg:shadow-none dark:bg-dark-800`}
        >
          <NavBarMenuList menu={menu} />
        </div>
      </div>
    </nav>
  );
}
