import { h, type FunctionComponent } 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'

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

const dateYear = new Date().getFullYear()

const EntriesPage: FunctionComponent = () => {
  const [journals, setJournals] = useState<Journal[]>([])
  const [financialYears, setFinancialYears] = useState<FinancialYear[]>([])
  const [entries, setEntries] = useState<Entry[]>([])

  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) as Record<string, string>

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

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

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

  useEffect(() => {
    rek(`/api/entries?journal=${selectedJournal}&year=${selectedYear}`).then(setEntries)
  }, [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 className='grid'>
        <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.journal}
                {entry.number}
              </td>
              <td>{entry.entryDate?.slice(0, 10)}</td>
              <td>{entry.transactionDate?.slice(0, 10)}</td>
              <td className='tar'>{entry.amount}</td>
              <td>{entry.description}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  ) : null
}

export default EntriesPage
