'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';

import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';

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

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

  const { data: transferToLaying, isLoading: isLoadingTransferToLaying } =
    useSWR(transferToLayingId, (id: number) =>
      TransferToLayingApi.getSingle(id)
    );

  if (!transferToLayingId) {
    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 (
    !isLoadingTransferToLaying &&
    (!transferToLaying || isResponseError(transferToLaying))
  ) {
    router.replace('/404');
    return;
  }

  if (
    isResponseSuccess(transferToLaying) &&
    transferToLaying.data.approval.step_number === 2
  ) {
    router.replace('/production/transfer-to-laying');
    return;
  }

  return (
    <div className='w-full p-4 flex flex-row justify-center'>
      {isLoadingTransferToLaying && (
        <span className='loading loading-spinner loading-xl' />
      )}
      {!isLoadingTransferToLaying && isResponseSuccess(transferToLaying) && (
        <TransferToLayingForm
          type='edit'
          initialValues={transferToLaying.data}
        />
      )}
    </div>
  );
};

export default TransferToLayingEdit;
