'use client';

import InventoryProductDetail from '@/components/pages/inventory/product/detail/InventoryProductDetail';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { InventoryProductApi } from '@/services/api/inventory';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

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

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

  const { data: inventoryProduct, isLoading: isLoadingInventoryProduct } =
    useSWR(inventoryProductId, (id: number) =>
      InventoryProductApi.getSingle(id)
    );

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

  return (
    <div className='size-full'>
      {isLoadingInventoryProduct && (
        <span className='loading loading-spinner loading-xl' />
      )}
      {!isLoadingInventoryProduct && isResponseSuccess(inventoryProduct) && (
        <InventoryProductDetail inventoryProduct={inventoryProduct.data} />
      )}
    </div>
  );
};

export default InventoryProductDetailPage;
