'use client';

import { usePathname, useRouter } from 'next/navigation';
import Drawer from '@/components/Drawer';
import React, { ReactNode } from 'react';
import ProjectFlockTable from '@/components/pages/production/project-flock/ProjectFlockTable';
import { useUiStore } from '@/stores/ui/ui.store';

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

  const isAdd = pathname.includes('/add');
  const isEdit = pathname.includes('/detail/edit');
  const isDetail = pathname.includes('/detail');
  const isChickin = pathname.includes('/chickin/add/kandang');
  const isClosing = pathname.includes('/closing');

  const isOpen = isAdd || isEdit || isDetail || isChickin || isClosing;

  const handleBackdropClick = () => {
    const unsub = useUiStore.getState().subscribeIsValid((isValid) => {
      if (isValid) {
        unsub(); // berhenti listen
        router.push('/production/project-flock');
      }
    });

    toggleValidate();
  };

  return (
    <>
      {/* List page always rendered */}
      <div className='min-h-sceen w-full relative'>
        <ProjectFlockTable
          refresh={() => !isOpen && router.push('/production/project-flock')}
        />
      </div>

      {/* Render Drawer only on /add */}
      <Drawer
        open={isOpen}
        setOpen={(v) => {
          if (!v) router.push('/production/project-flock');
        }}
        closeOnBackdropClick={isDetail ? true : false}
        onBackdropClick={handleBackdropClick}
        variant='right'
        zIndex='99999'
        sidebarContent={isOpen && <div className=''>{children}</div>}
      />
    </>
  );
}
