/* Copyright (C) 2024 Manuel Bustillo*/

'use client'

import { useState } from "react";
import InlineTextField from "../components/form/inlineTextField";
import TableOfContents from "../components/table-of-contents";
import { AbstractApi } from '@/app/api/abstract-api';
import { Expense, ExpenseSerializer } from '@/app/lib/expense';

export default function ExpensesTable() {
  const [expenses, setExpenses] = useState<Array<Expense>>([]);
  const [expensesLoaded, setExpensesLoaded] = useState(false);


  function refreshExpenses() {
    new AbstractApi<Expense>().getAll(new ExpenseSerializer(), (expenses: Expense[]) => {    
      setExpenses(expenses);
      setExpensesLoaded(true);
    });
  }

  !expensesLoaded && refreshExpenses();

  const api = new AbstractApi<Expense>();
  const serializer = new ExpenseSerializer();

  return (
    <TableOfContents
      headers={['Name', 'Amount (€)', 'Pricing Type']}
      caption='Expenses'
      elements={expenses}
      rowRender={(expense) => (
        <tr key={expense.id} className="bg-white border-b odd:bg-white odd:dark:bg-gray-900 even:bg-gray-50 even:dark:bg-gray-800">
          <th scope="row" className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
            <InlineTextField initialValue={expense.name} onChange={(value) => { expense.name = value; updateExpense(expense) }} />
          </th>
          <td className="px-6 py-4">
            <InlineTextField initialValue={expense.amount.toString()} onChange={(value) => { expense.amount = parseFloat(value); updateExpense(expense) }} />
          </td>
          <td>
            {expense.pricingType}
          </td>
        </tr>
      )}
    />
  );
}