import { h } from 'preact'
import { useEffect, useState } from 'preact/hooks'
import rek from 'rek'
import Head from './head.ts'
import Result from './result.tsx'
import Results from './results.tsx'
import { formatNumber } from '../utils/format_number.ts'
import s from './results_page.module.scss'

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

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

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

      <h1>Results</h1>
      {years.length && results.length && (
        <table className={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>{formatNumber(result[year])}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </section>
  )
}

export default ResultsPage
