import { receiveCustomerPayment } from "@/lib/actions";
import { formatCurrency, formatDate } from "@/lib/format";
import { getInvoices } from "@/lib/repository";

export default function InvoicesPage() {
  const invoices = getInvoices();

  return (
    <div className="grid">
      <section className="panel">
        <h2 className="section-title">Customer Invoices</h2>
        <p className="section-copy">Invoices are created automatically when shipped sales orders post accounts receivable.</p>
        <div className="table-wrap">
          <table className="table">
            <thead><tr><th>Invoice</th><th>Customer</th><th>Status</th><th>Invoice Date</th><th>Due</th><th>Total</th><th>Paid</th><th>Balance</th><th>Payment</th></tr></thead>
            <tbody>
              {invoices.length === 0 ? (
                <tr><td colSpan={9} className="muted">No invoices yet. Ship a sales order to create one.</td></tr>
              ) : (
                invoices.map((invoice) => (
                  <tr key={invoice.id}>
                    <td>{invoice.invoiceNumber}</td>
                    <td>{invoice.customerName}</td>
                    <td><span className={`pill ${invoice.status === "paid" ? "" : "warning"}`}>{invoice.status}</span></td>
                    <td>{formatDate(invoice.invoiceDate)}</td>
                    <td>{invoice.dueDate ? formatDate(invoice.dueDate) : "-"}</td>
                    <td>{formatCurrency(invoice.totalAmount)}</td>
                    <td>{formatCurrency(invoice.paidAmount)}</td>
                    <td>{formatCurrency(invoice.balanceDue)}</td>
                    <td>
                      {invoice.status === "paid" ? (
                        <span className="muted">Paid</span>
                      ) : (
                        <form action={receiveCustomerPayment} className="form-grid">
                          <input type="hidden" name="invoiceId" value={invoice.id} />
                          <input className="input" name="amount" type="number" min="0.01" step="0.01" defaultValue={invoice.balanceDue.toFixed(2)} />
                          <input className="input" name="notes" placeholder="Payment notes" />
                          <button className="button secondary" type="submit">Receive</button>
                        </form>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}
