import { h, type FunctionComponent } from 'preact'
import cn from 'classnames'
import rek from 'rek'
import Head from './head.ts'
import { formatNumber } from '../utils/format_number.ts'
import s from './balances_page.module.scss'
import usePromise from '../../shared/hooks/use_promise.ts'

import type { FinancialYear } from '../../../shared/types.db.ts'
import type { Balance } from '../../../shared/types.db_composite.ts'

const BalancesPage: FunctionComponent = () => {
  const [balances, years] = usePromise<[Balance[], number[]]>(() =>
    Promise.all([
      rek(`/api/balances`),
      rek(`/api/financial-years`).then((financialYears: FinancialYear[]) => financialYears.map((fy) => fy.year)),
    ]),
  )

  return (
    <section>
      <Head>
        <title> : Balances</title>
      </Head>

      <h1>Balances</h1>
      {years.length && balances.length && (
        <table className={cn('grid', s.table)}>
          <thead>
            <tr>
              <th>Account</th>
              <th>Description</th>
              {years.map((year) => (
                <th>{year}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {balances.map((balance) => (
              <tr>
                <td>{balance.accountNumber}</td>
                <td>{balance.description}</td>
                {years.map((year) => (
                  <td className='tar'>
                    <a href={`/transactions?year=${year}&accountNumber=${balance.accountNumber}`}>
                      {formatNumber(balance[year])}
                    </a>
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </section>
  )
}

export default BalancesPage
