'use client';

import ProductionStandardForm from '@/components/pages/master-data/production-standard/form/ProductionStandardForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { ProductionStandardApi } from '@/services/api/master-data';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

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

  // Get Query Params
  const productionStandardId = searchParams.get('productionStandardId');

  // Fetch Data
  const { data: productionStandard, isLoading: isLoadingProductionStandard } =
    useSWR(productionStandardId, (id: number) =>
      ProductionStandardApi.getSingle(id)
    );

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

  return (
    <>
      {isLoadingProductionStandard && (
        <span className='loading loading-spinner loading-xl' />
      )}
      {!isLoadingProductionStandard &&
        isResponseSuccess(productionStandard) && (
          <ProductionStandardForm
            formType='detail'
            initialValue={productionStandard.data}
          />
        )}
    </>
  );
};

export default DetailProductionStandardPage;
