'use client';

import { usePathname, useRouter } from 'next/navigation';
import Drawer from '@/components/Drawer';
import React, { ReactNode } from 'react';
import Uniformity from '@/app/production/uniformity/page';
import { useUiStore } from '@/stores/ui/ui.store';

export default function UniformityPageWrapper({
  children,
}: {
  children: ReactNode;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const toggleValidate = useUiStore((s) => s.toggleValidate);
  const setExpandedDrawerOpen = useUiStore((s) => s.setExpandedDrawerOpen);
  const expandedDrawerOpen = useUiStore((s) => s.expandedDrawerOpen);
  const expandedDrawerContent = useUiStore((s) => s.expandedDrawerContent);

  const isAdd = pathname.includes('/add');
  const isEdit = pathname.includes('/detail/edit');
  const isDetail = pathname.includes('/detail');

  const isOpen = isAdd || isEdit || isDetail;

  const handleBackdropClick = () => {
    const unsub = useUiStore.getState().subscribeIsValid((isValid) => {
      if (isValid) {
        router.push('/production/uniformity');
        unsub?.();
        setExpandedDrawerOpen(false);
      } else {
        unsub?.();
      }
    });

    toggleValidate();
  };

  return (
    <>
      <div className='w-full'>
        <Uniformity />
      </div>

      <Drawer
        open={isOpen}
        setOpen={(v) => {
          if (!v) {
            router.push('/production/uniformity');
            setExpandedDrawerOpen(false);
          }
        }}
        closeOnBackdropClick={isDetail ? true : false}
        onBackdropClick={handleBackdropClick}
        variant='right'
        zIndex='99999'
        sidebarContent={isOpen ? <div className=''>{children}</div> : null}
        expandedContent={expandedDrawerOpen ? expandedDrawerContent : null}
        className={{
          drawerSidebarContent: 'w-[446px]',
          drawerExpandedContent: 'w-[446px]',
        }}
      />
    </>
  );
}
