'use client';

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

import KandangForm from '@/components/pages/master-data/kandang/form/KandangForm';

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

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

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

  const { data: kandang, isLoading: isLoadingKandang } = useSWR(
    kandangId,
    (id: number) => KandangApi.getSingle(id)
  );

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

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

export default KandangDetail;
