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

export default function ProductsTab({
  productForm,
  setProductForm,
  editIds,
  setEditIds,
  saveProduct,
  products,
  filteredProducts,
  search,
  setSearch,
  loadData
}) {
  return (
    <section className="card">
      <h3>Products</h3>
      <form onSubmit={saveProduct} className="grid">
        <input
          placeholder="Product Name"
          value={productForm.productName}
          onChange={(e) => setProductForm({ ...productForm, productName: e.target.value })}
          required
        />
        <input
          type="number"
          placeholder="Quantity"
          value={productForm.productQuantity}
          onChange={(e) => setProductForm({ ...productForm, productQuantity: e.target.value })}
          required
        />
        <input
          type="number"
          step="0.01"
          placeholder="Unit Price"
          value={productForm.unitPrice}
          onChange={(e) => setProductForm({ ...productForm, unitPrice: e.target.value })}
          required
        />
        <button type="submit">{editIds.product ? "Update Product" : "Add Product"}</button>
      </form>

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

      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Qty</th>
            <th>Unit</th>
            <th>Total</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {filteredProducts.map((p) => (
            <tr key={p._id}>
              <td>{p.productName}</td>
              <td>{p.productQuantity}</td>
              <td>{p.unitPrice}</td>
              <td>{p.totalPrice}</td>
              <td>
                <button
                  type="button"
                  onClick={() => {
                    setProductForm({
                      productName: p.productName,
                      productQuantity: p.productQuantity,
                      unitPrice: p.unitPrice
                    });
                    setEditIds((s) => ({ ...s, product: p._id }));
                  }}
                >
                  Edit
                </button>
                <button
                  type="button"
                  onClick={async () => {
                    await api.del(`/products/${p._id}`);
                    await loadData();
                  }}
                >
                  Delete
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  );
}

