import { payVendorBill } from "@/lib/actions";
import { formatCurrency, formatDate } from "@/lib/format";
import { getVendorBills } from "@/lib/repository";

export default function VendorBillsPage() {
  const bills = getVendorBills();

  return (
    <div className="grid">
      <section className="panel">
        <h2 className="section-title">Vendor Bills</h2>
        <p className="section-copy">Vendor bills are created automatically when purchase order receipts post accounts payable.</p>
        <div className="table-wrap">
          <table className="table">
            <thead><tr><th>Bill</th><th>Vendor</th><th>Status</th><th>Bill Date</th><th>Due</th><th>Total</th><th>Paid</th><th>Balance</th><th>Payment</th></tr></thead>
            <tbody>
              {bills.length === 0 ? (
                <tr><td colSpan={9} className="muted">No vendor bills yet. Receive a purchase order to create one.</td></tr>
              ) : (
                bills.map((bill) => (
                  <tr key={bill.id}>
                    <td>{bill.billNumber}</td>
                    <td>{bill.vendorName}</td>
                    <td><span className={`pill ${bill.status === "paid" ? "" : "warning"}`}>{bill.status}</span></td>
                    <td>{formatDate(bill.billDate)}</td>
                    <td>{bill.dueDate ? formatDate(bill.dueDate) : "-"}</td>
                    <td>{formatCurrency(bill.totalAmount)}</td>
                    <td>{formatCurrency(bill.paidAmount)}</td>
                    <td>{formatCurrency(bill.balanceDue)}</td>
                    <td>
                      {bill.status === "paid" ? (
                        <span className="muted">Paid</span>
                      ) : (
                        <form action={payVendorBill} className="form-grid">
                          <input type="hidden" name="vendorBillId" value={bill.id} />
                          <input className="input" name="amount" type="number" min="0.01" step="0.01" defaultValue={bill.balanceDue.toFixed(2)} />
                          <input className="input" name="notes" placeholder="Payment notes" />
                          <button className="button secondary" type="submit">Pay</button>
                        </form>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}
