import { h } from 'preact'
import { useCallback, useEffect, useState } from 'preact/hooks'
import { useLocation } from 'preact-iso'
import { isEmpty } from 'lowline'
import qs from 'mini-qs'
import rek from 'rek'

import Head from './head.ts'
import serializeForm from '../../shared/utils/serialize_form.ts'

const dateYear = new Date().getFullYear()

const EntriesPage = () => {
  const [journals, setJournals] = useState([])
  const [financialYears, setFinancialYears] = useState([])
  const [entries, setEntries] = useState([])

  const location = useLocation()

  const { journal: selectedJournal = 'A', year: selectedYear = dateYear } = location.query

  const onSubmit = useCallback((e: SubmitEvent) => {
    e.preventDefault()

    const values = serializeForm(e.target as HTMLFormElement)

    const search = !isEmpty(values) ? '?' + qs.stringify(values) : ''

    location.route(`/entries${search}`)
  }, [])

  useEffect(() => {
    rek('/api/journals').then((journals) => {
      setJournals(journals)
    })
    rek('/api/financial-years').then((financialYears) => {
      setFinancialYears(financialYears.toReversed())
    })
  }, [])

  useEffect(() => {
    rek(`/api/entries?journal=${selectedJournal}&year=${selectedYear}`).then((entries) => setEntries(entries))
  }, [selectedJournal, selectedYear])

  return financialYears.length && journals.length ? (
    <section>
      <Head>
        <title> : Entries</title>
      </Head>
      <h1>Entries</h1>

      <form onSubmit={onSubmit}>
        <select defaultValue='D' name='journal'>
          {/*<option value='A'>A</option>
            <option value='D'>D</option>*/}
          {journals.map((journal) => (
            <option value={journal.identifier}>{journal.identifier}</option>
          ))}
        </select>
        <select name='year' defaultValue={selectedYear}>
          {financialYears.map((financialYear) => (
            <option value={financialYear.year}>{financialYear.year}</option>
          ))}
        </select>
        <button>Search</button>
      </form>

      <h2>
        {selectedJournal} : {selectedYear}
      </h2>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Number</th>
            <th>Entry Date</th>
            <th>Transaction Date</th>
            <th>Amount</th>
            <th>Description</th>
          </tr>
        </thead>
        <tbody>
          {entries?.map((entry) => (
            <tr>
              <td>
                <a href={`/entries/${entry.id}`}>{entry.id}</a>
              </td>
              <td>{entry.number}</td>
              <td>{entry.entryDate?.slice(0, 10)}</td>
              <td>{entry.transactionDate?.slice(0, 10)}</td>
              <td>{entry.amount}</td>
              <td>{entry.description}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  ) : null
}

export default EntriesPage
