'use client';

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

import ProductForm from '@/components/pages/master-data/product/form/ProductForm';
import { ProductApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';

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

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

  const { data: product, isLoading } = useSWR(productId, (id: number) =>
    ProductApi.getSingle(id)
  );

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

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

export default ProductDetail;
