'use client';

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

import ProductCategoryForm from '@/components/pages/master-data/product-category/form/ProductCategoryForm';

import { ProductCategoryApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';

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

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

  const { data: productCategory, isLoading: isLoadingProductCategory } = useSWR(
    productCategoryId,
    (id: number) => ProductCategoryApi.getSingle(id)
  );

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

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

export default ProductCategoryDetail;
