'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 PermissionNotFound from '@/components/helper/PermissionNotFound';

import { useUiStore } from '@/stores/ui/ui.store';
import { MAIN_DRAWER_LINKS } from '@/config/constant';
import { isPathActive } from '@/lib/helper';
import { ROUTE_PERMISSIONS } from '@/config/route-permission';
import { useAuth } from '@/services/hooks/useAuth';

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

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

  return (
    <div className='w-full flex flex-col'>
      <div className='p-3 flex flex-row items-center gap-4 border-b border-base-content/10'>
        <div className='flex flex-row items-center gap-2'>
          <Image
            src='/assets/img/lti-logo.png'
            alt='LTI Logo'
            width={40}
            height={40}
            className='w-full max-w-10 h-auto'
          />

          <div className='font-roboto'>
            <h1 className='text-sm font-semibold'>LTI ERP</h1>
            <p className='text-sm text-black/50'>Lumbung Telur Indonesia</p>
          </div>
        </div>

        <div className='grow flex flex-row justify-end sm:hidden'>
          <Button
            variant='soft'
            color='error'
            onClick={closeMainDrawerHandler}
            className='p-1 rounded-full'
          >
            <Icon
              icon='material-symbols:close-rounded'
              width={16}
              height={16}
            />
          </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 { permissionCheck } = useAuth();

  const formattedPathname = pathname.endsWith('/') ? pathname : `${pathname}/`;

  const isPermitted = ROUTE_PERMISSIONS[formattedPathname]?.some((permission) =>
    permissionCheck(permission)
  );

  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);
  };

  if (!isPermitted) {
    return <PermissionNotFound />;
  }

  return (
    <Drawer
      open={mainDrawerOpen}
      setOpen={setMainDrawerOpen}
      openOnLarge
      sidebarContent={<MainDrawerContent />}
      className={{
        drawerSide: 'border-r border-base-content/10',
        drawerSidebarContent: 'min-w-[244px] lg:w-[244px]',
      }}
    >
      <main className='w-full h-full flex flex-col'>
        <Navbar title={pageTitle as string} toggleSidebar={toggleSidebar} />

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

export default MainDrawer;
