'use client';

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

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 formModal = useModal();

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

    toggleValidate();
  };

  useEffect(() => {
    if (isOpen && !formModal.open) {
      formModal.openModal();
    } else {
      formModal.closeModal();
    }
  }, [isOpen]);

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

      {/* Render Modal only on /add */}
      <Modal
        ref={formModal.ref}
        position='end'
        onBackdropClick={handleBackdropClick}
        className={{
          modalBox: 'w-full sm:w-fit p-3 rounded-xl bg-transparent shadow-none',
        }}
      >
        <div className='w-full sm:w-[446px] h-full flex flex-col sm:flex-row items-stretch bg-base-100 rounded-xl overflow-hidden'>
          {isOpen && children}
        </div>
      </Modal>
    </>
  );
}
