'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import PurchaseRequestForm from '@/components/pages/purchase/form/request/PurchaseRequestForm';
import { PurchaseRequestApi } from '@/services/api/purchase';
import { isResponseSuccess, isResponseError } from '@/lib/api-helper';

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

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

  const { data: purchase, isLoading: isLoadingPurchase } = useSWR(
    purchaseId,
    (id: number) => PurchaseRequestApi.getSingle(id)
  );

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

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

export default PurchaseEdit;
