import { h, type FunctionComponent } from 'preact'
import type { Selectable } from 'kysely'
import { useEffect, useState } from 'preact/hooks'
import rek from 'rek'

import type { Transaction } from '../../../shared/types.db.ts'

interface ObjectComponentProps {
  objectId: number
}

const ObjectComponent: FunctionComponent<ObjectComponentProps> = ({ objectId }) => {
  const [transactions, setTransactions] = useState<Selectable<Transaction>[]>([])

  useEffect(() => {
    rek(`/api/objects/${objectId}`).then(setTransactions)
  }, [objectId])

  return (
    <table className='grid'>
      <thead>
        <tr>
          <th>Entry</th>
          <th>Date</th>
          <th>Account</th>
          <th>Amount</th>
        </tr>
      </thead>
      <tbody>
        {transactions.map((transaction) => (
          <tr>
            <td>
              <a href={`/entries/${transaction.entryId}`}>{transaction.entryId}</a>
            </td>
            <td>{(transaction.transactionDate as unknown as string)?.slice(0, 10)}</td>
            <td>{transaction.accountNumber}</td>
            <td className='tar'>{transaction.amount}</td>
          </tr>
        ))}
      </tbody>
    </table>
  )
}

export default ObjectComponent
