import { shipSalesOrder } from "@/lib/actions";
import { SalesOrderForm } from "@/components/sales-order-form";
import { formatCurrency, formatDate } from "@/lib/format";
import { getCustomers, getOrderItemOptions, getSalesOrders } from "@/lib/repository";

export default function SalesOrdersPage() {
  const customers = getCustomers();
  const items = getOrderItemOptions();
  const orders = getSalesOrders();

  return (
    <div className="grid">
      <section className="two-up">
        <article className="panel">
          <h2 className="section-title">Create Sales Order</h2>
          <p className="section-copy">Build the order from real inventory records so each line references an actual item in the database.</p>
          <SalesOrderForm customers={customers} items={items} />
        </article>
        <article className="panel">
          <h2 className="section-title">Shipping Flow</h2>
          <p className="section-copy">Leave line quantities blank to ship the remaining balance, or enter `SKU,quantity` rows for a partial shipment.</p>
          <div className="table-wrap">
            <table className="table">
              <thead><tr><th>Order</th><th>Customer</th><th>Status</th><th>Total</th><th>Qty Progress</th><th>Created</th><th>Action</th></tr></thead>
              <tbody>
                {orders.length === 0 ? (
                  <tr><td colSpan={7} className="muted">No sales orders yet.</td></tr>
                ) : (
                  orders.map((order) => (
                    <tr key={order.id}>
                      <td>{order.orderNumber}</td>
                      <td>{order.customerName}</td>
                      <td><span className={`pill ${order.status === "shipped" ? "" : "warning"}`}>{order.status}</span></td>
                      <td>{formatCurrency(order.totalAmount)}</td>
                      <td>{order.fulfilledQuantity} / {order.orderedQuantity}</td>
                      <td>{formatDate(order.createdAt)}</td>
                      <td>
                        {order.status === "shipped" ? (
                          <span className="muted">Shipped</span>
                        ) : (
                          <form action={shipSalesOrder} className="form-grid">
                            <input type="hidden" name="orderId" value={order.id} />
                            <textarea className="textarea" name="lines" placeholder={"PART-001,1\nKIT-100,2"} />
                            <button className="button secondary" type="submit">Ship</button>
                          </form>
                        )}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </article>
      </section>
    </div>
  );
}
