'use client';

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

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

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

const ExpenseEditPage = () => {
  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 isExpenseCanBeEdited =
    !isLoadingExpense &&
    isResponseSuccess(expense) &&
    expense.data.latest_approval.step_number !== 5 &&
    expense.data.latest_approval.step_number !== 6 &&
    (expense.data.latest_approval.step_number === 1 ||
      expense.data.latest_approval.step_number === 2 ||
      expense.data.latest_approval.step_number === 3 ||
      expense.data.latest_approval.step_number === 4);

  if (!isLoadingExpense && !isExpenseCanBeEdited) {
    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) && (
        <ExpenseRequestForm type='edit' initialValues={expense.data} />
      )}
    </div>
  );
};

export default ExpenseEditPage;
