import { h } from 'preact'
import { useEffect, useState } from 'preact/hooks'
import { useRoute } from 'preact-iso'
import { formatNumber } from '../utils/format_number.ts'
import rek from 'rek'

import { type Entry } from '../../../shared/types.ts'

import Head from './head.ts'

const EntriesPage = () => {
  const [entry, setEntry] = useState<Entry>(null)
  const route = useRoute()

  useEffect(() => {
    rek(`/api/entries/${route.params.id}`).then((entry) => {
      setEntry(entry)
    })
  }, [])

  if (!entry) return

  return (
    <section>
      <Head>
        <title>
          {' '}
          : Entry {entry.journal} {entry.number}{' '}
        </title>
      </Head>
      <h1>
        Entry {entry.journal} {entry.number}
      </h1>

      <table className='grid'>
        <thead>
          <tr>
            <th>ID</th>
            <th>Journal</th>
            <th>Number</th>
            <th>Entry Date</th>
            <th>Transaction Date</th>
            <th>Amount</th>
            <th>Description</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>
              <a href={`/entries/${entry.id}`}>{entry.id}</a>
            </td>
            <td>{entry.journal}</td>
            <td>{entry.number}</td>
            <td>{entry.entryDate?.slice(0, 10)}</td>
            <td>{entry.transactionDate?.slice(0, 10)}</td>
            <td className='tar'>{entry.amount}</td>
            <td>{entry.description}</td>
          </tr>
        </tbody>
      </table>

      <h2>Transactions</h2>
      <table className='grid'>
        <thead>
          <tr>
            <th>Account</th>
            <th>Debit</th>
            <th>Credit</th>
            <th>Description</th>
          </tr>
        </thead>
        <tbody>
          {entry?.transactions?.map((transaction) => (
            <tr>
              <td>{transaction.account_number}</td>
              <td className='tar'>{transaction.amount >= 0 ? formatNumber(transaction.amount) : null}</td>
              <td className='tar'>{transaction.amount < 0 ? formatNumber(Math.abs(transaction.amount)) : null}</td>
              <td>{transaction.description}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  )
}

export default EntriesPage
