'use client';

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

import UomForm from '@/components/pages/master-data/uom/form/UomForm';

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

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

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

  const { data: uom, isLoading: isLoadingUom } = useSWR(uomId, (id: number) =>
    UomApi.getSingle(id)
  );

  if (!uomId) {
    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 (!isLoadingUom && !uom) {
    router.replace('/404');
    return;
  }

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

export default UomDetail;
