'use client';

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

import NonstockForm from '@/components/pages/master-data/nonstock/form/NonstockForm';

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

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

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

  const { data: nonstock, isLoading: isLoadingNonstock } = useSWR(
    nonstockId,
    (id: number) => NonstockApi.getSingle(id)
  );

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

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

export default NonstockDetail;
