'use client';

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

import FcrForm from '@/components/pages/master-data/fcr/form/FcrForm';

import { FcrApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { BaseApiResponse } from '@/types/api/api-general';
import { FcrWithStandards } from '@/types/api/master-data/fcr';

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

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

  const { data: fcr, isLoading: isLoadingFcr } = useSWR(
    fcrId,
    (id: number) =>
      FcrApi.getSingle(id) as Promise<
        BaseApiResponse<FcrWithStandards> | undefined
      >
  );

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

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

export default FcrEdit;
