'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 { isResponseError, isResponseSuccess } from '@/lib/api-helper';

const UomEdit = () => {
  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 || isResponseError(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='edit' initialValues={uom.data} />
      )}
    </div>
  );
};

export default UomEdit;
