'use client';

import ChickinForm from '@/components/pages/production/chickin/form/ChickinForm';
import { isResponseSuccess } from '@/lib/api-helper';
import { ProjectFlockKandangApi } from '@/services/api/production';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

export default function AddChickinKandang() {
  const searchParams = useSearchParams();
  const projectFlockKandangId = searchParams.get('projectFlockKandangId');
  const projectFlockId = searchParams.get('projectFlockId');
  const router = useRouter();

  const {
    data: projectFlockKandang,
    isLoading: isLoading,
    mutate: refreshProjectFlockKandang,
  } = useSWR(
    `get-single-project-flock-kandang/${projectFlockKandangId}`,
    async () =>
      ProjectFlockKandangApi.getSingle(
        parseInt(projectFlockKandangId as string)
      )
  );

  if (!projectFlockKandangId) {
    router.push(`/production/chickin/add?projectFlockId=${projectFlockId}`);
    return (
      <div className='w-full flex flex-row justify-center items-center p-4'>
        <span className='loading loading-spinner loading-xl' />
      </div>
    );
  }

  if (!isLoading && !projectFlockKandang) {
    router.replace('/404');
    return;
  }

  const handleAfterSubmit = () => {
    refreshProjectFlockKandang();
  };

  return (
    <>
      <section className='size-full'>
        {isLoading && <span className='loading loading-spinner loading-xl' />}
        {!isLoading &&
          isResponseSuccess(projectFlockKandang) &&
          projectFlockId && (
            <ChickinForm
              initialValues={projectFlockKandang.data}
              afterSubmit={handleAfterSubmit}
            />
          )}
      </section>
    </>
  );
}
