'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import { FinanceApi } from '@/services/api/finance';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import FormFinanceAddInitialBalance from '@/components/pages/finance/add/initial-balance/FormFinanceAddInitialBalance';

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

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

  const { data: finance, isLoading: isLoadingFinance } = useSWR(
    financeId,
    (id: number) => FinanceApi.getSingle(id)
  );

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

  return (
    <div className='w-full p-4 flex flex-row justify-center'>
      {isLoadingFinance && (
        <span className='loading loading-spinner loading-xl' />
      )}

      {!isLoadingFinance && (
        <FormFinanceAddInitialBalance
          type='edit'
          initialValues={isResponseSuccess(finance) ? finance.data : undefined}
        />
      )}
    </div>
  );
};

export default EditFinanceInitialBalancePage;
