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

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

  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">Ship relational order lines directly by choosing quantities from the remaining balance on each line.</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>
                        ) : (
                          <SalesOrderFulfillmentForm
                            orderId={order.id}
                            lines={orderLines.filter((line) => line.salesOrderId === order.id && line.remainingQuantity > 0)}
                          />
                        )}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </article>
      </section>
    </div>
  );
}
