import { h, type FunctionComponent } from 'preact'
// @ts-ignore
import Format from 'easy-tz/format'
import { useRoute } from 'preact-iso'
import rek from 'rek'
import Head from './head.ts'
import usePromise from '../../shared/hooks/use_promise.ts'
import type { File, Invoice, Supplier } from '../../../shared/types.db.ts'
import { formatPrice } from '../utils/format_number.ts'

const format = Format.bind(null, null, 'YYYY.MM.DD')

const InvoicesPage: FunctionComponent = () => {
  const route = useRoute()

  const [supplier, { data: invoices }, totalAmount] = usePromise<
    [Supplier, { data: (Invoice & { files?: File[] })[] }, number]
  >(() =>
    Promise.all([
      rek(`/api/suppliers/${route.params.supplier}`),
      rek(`/api/invoices?supplierId=${route.params.supplier}`),
      rek(`/api/invoices/total-amount?supplierId=${route.params.supplier}`).then(
        (totalAmount: { totalAmount: number }) => totalAmount.totalAmount,
      ),
    ]),
  )

  return (
    <section>
      <Head>
        <title> : Fakturor : {supplier?.name}</title>
      </Head>

      <h1>Fakturor från {supplier?.name}</h1>

      <p>
        <strong>Total: {formatPrice(totalAmount)}</strong>
      </p>

      <table className='grid'>
        <thead>
          <tr>
            <th>ID</th>
            <th>Fisken</th>
            <th>PHM</th>
            <th>Fakturadatum</th>
            <th>Förfallodag</th>
            <th>Nummer</th>
            <th>Belopp</th>
            <th>Filer</th>
          </tr>
        </thead>
        <tbody>
          {invoices.map((invoice) => (
            <tr>
              <td>
                <a href={`/invoices/${invoice.id}`}>{invoice.id}</a>
              </td>
              <td>{invoice.fiskenNumber}</td>
              <td>{invoice.phmNumber}</td>
              <td>{format(invoice.invoiceDate)}</td>
              <td>{invoice.dueDate && format(invoice.dueDate)}</td>
              <td>{invoice.invoiceNumber}</td>
              <td>{invoice.amount}</td>
              <td>
                {invoice.files?.map((file) => (
                  <a href={`/uploads/invoices/${file.filename}`} target='_blank'>
                    {file.filename}
                  </a>
                ))}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  )
}

export default InvoicesPage
