'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 ExpenseRealization = () => {
  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 isExpenseCanBeRealized =
    isResponseSuccess(expense) &&
    expense.data.latest_approval.action !== 'REJECTED' &&
    expense.data.latest_approval.step_number === 4;

  if (isResponseSuccess(expense) && !isExpenseCanBeRealized) {
    if (typeof window !== 'undefined') {
      router.back();
    }

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

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

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

export default ExpenseRealization;
