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

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

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

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

export default ResultsPage
