'use client';

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

import ExpenseRealizationForm from '@/components/pages/expense/form/ExpenseRealizationForm';

import { ExpenseApi } from '@/services/api/expense';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';

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

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

  const { data: expense, isLoading: isLoadingExpense } = useSWR(
    expenseId,
    (id: number) => ExpenseApi.getSingle(id)
  );

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

  const isExpenseRealizationCanBeEdited =
    !isLoadingExpense &&
    isResponseSuccess(expense) &&
    expense.data.latest_approval.action !== 'REJECTED' &&
    (expense.data.latest_approval.step_number === 5 ||
      expense.data.latest_approval.step_number === 6);

  if (!isLoadingExpense && !isExpenseRealizationCanBeEdited) {
    router.back();
    return;
  }

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

      {!isLoadingExpense && isResponseSuccess(expense) && (
        <ExpenseRealizationForm type='edit' initialValues={expense.data} />
      )}
    </div>
  );
};

export default ExpenseRealizationEditPage;
