'use client';
import ProjectFlockClosingForm from '@/components/pages/production/project-flock/closing/ProjectFlockClosingForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { ProjectFlockKandangApi } from '@/services/api/production';
import { ProjectFlockApi } from '@/services/api/production/project-flock';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

const ProjectFlockClosingPage = () => {
  const router = useRouter();
  const searchParams = useSearchParams();

  const projectFlockId = searchParams.get('projectFlockId');
  const projectFlockKandangId = searchParams.get('projectFlockKandangId');

  const { data: projectFlockKandang, isLoading: isLoadingProjectFlockKandang } =
    useSWR(projectFlockKandangId, (id: number) =>
      ProjectFlockKandangApi.getSingle(id)
    );

  const { data: projectFlock, isLoading: isLoadingProjectFlock } = useSWR(
    projectFlockId,
    (id: number) => ProjectFlockApi.getSingle(id)
  );

  if (!projectFlockId || !projectFlockKandangId) {
    router.back();

    return (
      <div className='w-full flex flex-row justify-center items-center p-4'>
        <span className='loading loading-spinner loading-xl' />
      </div>
    );
  }

  if (
    !isLoadingProjectFlock &&
    (!projectFlock || isResponseError(projectFlock)) &&
    !isLoadingProjectFlockKandang &&
    (!projectFlockKandang || isResponseError(projectFlockKandang))
  ) {
    router.replace('/404');
    return;
  }

  return (
    <div className='w-full h-full flex flex-col justify-center'>
      {isLoadingProjectFlock ||
        (isLoadingProjectFlockKandang && (
          <span className='loading loading-spinner loading-xl' />
        ))}
      {isResponseSuccess(projectFlock) &&
        isResponseSuccess(projectFlockKandang) && (
          <ProjectFlockClosingForm
            projectFlock={projectFlock.data}
            projectFlockKandang={projectFlockKandang.data}
          />
        )}
    </div>
  );
};

export default ProjectFlockClosingPage;
