'use client';

import { useCallback } from 'react';
import { usePathname } from 'next/navigation';

import Image from 'next/image';
import { Icon } from '@iconify/react';
import Drawer from '@/components/Drawer';
import Navbar from '@/components/Navbar';
import Button from '@/components/Button';
import SidebarMenu from '@/components/molecules/SidebarMenu';

import { useUiStore } from '@/stores/ui/ui.store';
import { MAIN_DRAWER_LINKS } from '@/config/constant';
import { isPathActive } from '@/lib/helper';

const MainDrawerContent = () => {
  const pathname = usePathname();
  const { setMainDrawerOpen } = useUiStore();

  const closeMainDrawerHandler = () => {
    setMainDrawerOpen(false);
  };

  return (
    <div className='w-full p-4 flex flex-col gap-4'>
      <div className='flex flex-row items-center gap-4'>
        <Image
          src='/assets/img/lti-logo.png'
          alt='MBU Logo'
          width={256}
          height={256}
          className='w-full max-w-16 h-auto'
        />

        <h1 className='text-xl font-bold'>LTI ERP</h1>

        <div className='grow flex flex-row justify-end sm:hidden'>
          <Button
            variant='soft'
            color='error'
            onClick={closeMainDrawerHandler}
            className='rounded-full'
          >
            <Icon
              icon='material-symbols:close-rounded'
              width={24}
              height={24}
            />
          </Button>
        </div>
      </div>

      <SidebarMenu menu={MAIN_DRAWER_LINKS} activeLink={pathname} />
    </div>
  );
};
const MainDrawer = ({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) => {
  const { mainDrawerOpen, setMainDrawerOpen } = useUiStore();
  const pathname = usePathname();

  const getPageTitle = useCallback(() => {
    let title = '';

    const activeMenu = MAIN_DRAWER_LINKS.find((item) =>
      isPathActive(pathname, item.link)
    );

    const traverseMenuTitle = (menu: typeof activeMenu) => {
      if (!menu) return;

      const hasSubmenu = menu?.submenu && menu?.submenu.length > 0;

      if (!title) {
        title += menu?.text;
      } else {
        title += ' - ' + menu?.text;
      }

      if (!hasSubmenu || !menu.submenu) return;

      const activeSubmenu = menu.submenu?.find((item) =>
        isPathActive(pathname, item.link)
      );

      traverseMenuTitle(activeSubmenu);
    };

    traverseMenuTitle(activeMenu);

    return title;
  }, [pathname]);

  const pageTitle = getPageTitle();

  const toggleSidebar = () => {
    setMainDrawerOpen(!mainDrawerOpen);
  };

  return (
    <Drawer
      open={mainDrawerOpen}
      setOpen={setMainDrawerOpen}
      openOnLarge
      sidebarContent={<MainDrawerContent />}
    >
      <main className='w-full h-full flex flex-col'>
        <Navbar title={pageTitle as string} toggleSidebar={toggleSidebar} />

        {children}
      </main>
    </Drawer>
  );
};

export default MainDrawer;
