'use client';

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

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

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

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

  if (!projectFlockId) {
    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))
  ) {
    router.replace('/404');
    return;
  }

  return (
    <div className='w-full flex flex-col justify-center'>
      {isLoadingProjectFlock && (
        <span className='loading loading-spinner loading-xl' />
      )}
      {!isLoadingProjectFlock && isResponseSuccess(projectFlock) && (
        <ProjectFlockForm formType='edit' initialValues={projectFlock.data} />
      )}
    </div>
  );
};

export default ProjectFlockEdit;
