'use client';

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

import ExpenseDetail from '@/components/pages/expense/ExpenseDetail';

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

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

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

  const { data: expense, isLoading: isLoadingExpense } = useSWR(
    ['expense-detail', expenseId],
    ([_, id]) => ExpenseApi.getSingle(Number(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;
  }

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

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

export default ExpenseDetailPage;
