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

const ResultsPage = () => {
  const [financialYears, setFinancialYears] = useState([])
  const [currentYear, setCurrentYear] = useState<number>(null)

  useEffect(() => {
    rek('/api/financial-years').then((financialYears) => {
      setFinancialYears(financialYears)
      setCurrentYear(financialYears[financialYears.length - 1].year)
    })
  }, [])

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

      <h1>Results</h1>
      <div className={s.years}>
        {financialYears.map((financialYear) => (
          <button onClick={() => setCurrentYear(financialYear.year)}>{financialYear.year}</button>
        ))}
      </div>
      {currentYear ? (
        <div>
          <h2>{currentYear}</h2>
          <Result year={currentYear} />
        </div>
      ) : null}
    </section>
  )
}

export default ResultsPage
