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 { Invoice, Supplier } from '../../../shared/types.ts'

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

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

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

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

      <h1>Invoices for {supplier?.name}</h1>

      <p>
        <strong>Total: {totalAmount}</strong>
      </p>

      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Fisken</th>
            <th>PHM</th>
            <th>Invoice Date</th>
            <th>Due Date</th>
            <th>Number</th>
            <th>Amount</th>
            <th>Files</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
