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 './results_page.module.scss'

import type { FinancialYear, Result } from '../../../shared/types.ts'

const ResultsPage: FunctionComponent = () => {
  const [results, setResults] = useState<Result[]>([])
  const [years, setYears] = useState<number[]>([])

  useEffect(() => {
    rek(`/api/results`).then((results: Result[]) => setResults(results))
    rek(`/api/financial-years`).then((financialYears: FinancialYear[]) => setYears(financialYears.map((fy) => fy.year)))
  }, [])

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

      <h1>Results</h1>
      {years.length && results.length && (
        <table className={cn('grid', s.table)}>
          <thead>
            <tr>
              <th>Account</th>
              <th>Description</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
