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'
import { formatNumber } from '../utils/format_number.ts'

const TransactionsPage = () => {
  const [financialYears, setFinancialYears] = useState([])
  const [transactions, setTransactions] = useState([])

  const location = useLocation()

  console.log(location)

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

    const values = serializeForm(e.target as HTMLFormElement)

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

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

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

  useEffect(() => {
    const search = location.url.split('?')[1] || ''

    rek(`/api/transactions${search ? '?' + search : ''}`).then((transactions) => {
      setTransactions(transactions)
    })
  }, [location.url])

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

      <form onSubmit={onSubmit}>
        <select name='year' defaultValue={location.query.year || '2025'}>
          {financialYears.map((financialYear) => (
            <option value={financialYear.year}>{financialYear.year}</option>
          ))}
        </select>
        <input type='text' name='accountNumber' defaultValue={location.query.accountNumber || ''} />
        <button>Search</button>
      </form>

      <h1>Transactions</h1>
      <div>
        <table className='grid'>
          <thead>
            <th>Date</th>
            <th>Account</th>
            <th>Debit</th>
            <th>Credit</th>
            <th>Description</th>
            <th>Entry</th>
            <th>Entry Description</th>
            <th>Invoice</th>
          </thead>
          <tbody>
            {transactions.map((transaction) => (
              <tr>
                <td>{transaction.transactionDate.slice(0, 10)}</td>
                <td>{transaction.accountNumber}</td>
                <td className='tar'>{transaction.amount >= 0 ? formatNumber(transaction.amount) : null}</td>
                <td className='tar'>{transaction.amount < 0 ? formatNumber(Math.abs(transaction.amount)) : null}</td>
                <td>{transaction.description}</td>
                <td>
                  <a href={`/entries/${transaction.entryId}`}>{transaction.entryId}</a>
                </td>
                <td>{transaction.entryDescription}</td>
                <td>
                  <a href={`/invoices/${transaction.invoiceId}`}>{transaction.invoiceId}</a>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  )
}

export default TransactionsPage
