'use client';

import FlockForm from '@/components/pages/master-data/flock/form/FlockForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { FlockApi } from '@/services/api/master-data';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

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

  // Get Query Params
  const flockId = searchParams.get('flockId');

  // Fetch Data
  const { data: flock, isLoading: isLoadingFlock } = useSWR(
    flockId,
    (id: number) => FlockApi.getSingle(id)
  );

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

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

export default FlockEdit;
