'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import PurchaseOrderDetail from '@/components/pages/purchase/order/PurchaseOrderDetail';
import { PurchaseApi } from '@/services/api/purchase';
import { isResponseSuccess, isResponseError } from '@/lib/api-helper';

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

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

  const {
    data: purchase,
    isLoading: isLoadingPurchase,
    mutate: mutatePurchase,
  } = useSWR(purchaseId, (id: number) => PurchaseApi.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'>
      {isLoadingPurchase && (
        <div className='w-full flex flex-row justify-center items-center'>
          <span className='loading loading-spinner loading-xl' />
        </div>
      )}
      {!isLoadingPurchase && isResponseSuccess(purchase) && (
        <PurchaseOrderDetail
          type='detail'
          initialValues={purchase.data}
          refetchData={mutatePurchase}
        />
      )}
    </div>
  );
};

export default PurchaseDetail;
