'use client';

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

import AreaForm from '@/components/pages/master-data/area/form/AreaForm';

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

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

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

  const { data: area, isLoading: isLoadingArea } = useSWR(
    areaId,
    (id: number) => AreaApi.getSingle(id)
  );

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

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

export default AreaDetail;
