import React from "react";
import { api } from "../../api";

export default function OrdersTab({
  orderForm,
  setOrderForm,
  editIds,
  setEditIds,
  saveOrder,
  orders,
  filteredOrders,
  search,
  setSearch,
  loadData,
  formatDateSafe,
}) {
  return (
    <section className="card">
      <h3>Orders</h3>
      <form onSubmit={saveOrder} className="grid">
        <input
          type="date"
          value={orderForm.order_date}
          onChange={(e) => setOrderForm({ ...orderForm, order_date: e.target.value })}
          required
        />
        <button type="submit">{editIds.order ? "Update Order" : "Add Order"}</button>
      </form>

      <input
        placeholder="Search orders..."
        value={search.orders}
        onChange={(e) => setSearch((s) => ({ ...s, orders: e.target.value }))}
      />

      <table>
        <thead>
          <tr>
            <th>Order Number</th>
            <th>Order Date</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {filteredOrders.map((o) => (
            <tr key={o._id}>
              <td>{o.order_number || o._id.slice(-6).toUpperCase()}</td>
              <td>{formatDateSafe(o.order_date)}</td>
              <td>
                <button
                  type="button"
                  onClick={() => {
                    const day = formatDateSafe(o.order_date);
                    setOrderForm({
                      ...orderForm,
                      order_date: day === "-" ? "" : day
                    });
                    setEditIds((s) => ({ ...s, order: o._id }));
                  }}
                >
                  Edit
                </button>
                <button
                  type="button"
                  onClick={async () => {
                    await api.del(`/orders/${o._id}`);
                    await loadData();
                  }}
                >
                  Delete
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  );
}

