'use client';

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

import LocationForm from '@/components/pages/master-data/location/form/LocationForm';

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

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

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

  const { data: location, isLoading: isLoadingLocation } = useSWR(
    locationId,
    (id: number) => LocationApi.getSingle(id)
  );

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

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

export default LocationEdit;
