/* Copyright (C) 2024-2025 LibreWeddingPlanner contributors*/

'use client'

import { AbstractApi } from '@/app/api/abstract-api';
import { Expense, ExpenseSerializer } from '@/app/lib/expense';
import { classNames } from '@/app/ui/components/button';
import ExpenseFormDialog from '@/app/ui/components/expense-form-dialog';
import ExpensesTable from '@/app/ui/expenses/table';
import SkeletonTable from '@/app/ui/guests/skeleton-row';
import { Suspense, useEffect, useState } from 'react';

export default function Page() {
  const refreshExpenses = () => {
    new AbstractApi<Expense>().getAll(new ExpenseSerializer(), (expenses: Expense[]) => {
      setExpenses(expenses);
    });
  }

  const [expenses, setExpenses] = useState<Expense[]>([]);
  const [expenseBeingEdited, setExpenseBeingEdited] = useState<Expense | undefined>(undefined);
  useEffect(() => { refreshExpenses() }, []);

  return (
    <div className="w-full">
      <div className="flex flex-col w-full items-center justify-between">
        <button onClick={() => setExpenseBeingEdited({})} className={classNames('primary')}>Add new</button>
        <ExpenseFormDialog
          key={expenseBeingEdited?.id}
          onCreate={() => { refreshExpenses(); setExpenseBeingEdited(undefined) }}
          expense={expenseBeingEdited}
          visible={expenseBeingEdited !== undefined}
          onHide={() => { setExpenseBeingEdited(undefined) }}
        />
        <Suspense fallback={<SkeletonTable />}>
          <ExpensesTable
            expenses={expenses}
            onUpdate={refreshExpenses}
            onEdit={(expense) => setExpenseBeingEdited(expense)}
          />
        </Suspense>
      </div>
    </div>
  );
}