import { h, type FunctionComponent } from 'preact'
import { useEffect, useState } from 'preact/hooks'
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 type { Balance, FinancialYear } from '../../../shared/types.ts'

const BalancesPage: FunctionComponent = () => {
  const [balances, setBalances] = useState<Balance[]>([])
  const [years, setYears] = useState<number[]>([])

  useEffect(() => {
    rek(`/api/balances`).then(setBalances)
    rek(`/api/financial-years`).then((financialYears: FinancialYear[]) => setYears(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
