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

export default function CustomersTab({
  customerForm,
  setCustomerForm,
  editIds,
  setEditIds,
  saveCustomer,
  products,
  orders,
  filteredCustomers,
  search,
  setSearch,
  onProductChange,
  onQuantityChange,
  onOrderChange,
  selectedProduct,
  formatDateSafe,
  ordersLoaded,
  loadData
}) {
  return (
    <section className="card">
      <h3>Customers</h3>
      <form onSubmit={saveCustomer} className="grid">
        <input
          placeholder="First Name"
          value={customerForm.cust_fname}
          onChange={(e) => setCustomerForm({ ...customerForm, cust_fname: e.target.value })}
          required
          aria-label="First Name"
        />
        <input
          placeholder="Last Name"
          value={customerForm.cust_lname}
          onChange={(e) => setCustomerForm({ ...customerForm, cust_lname: e.target.value })}
          required
          aria-label="Last Name"
        />
        <input
          placeholder="Location"
          value={customerForm.location}
          onChange={(e) => setCustomerForm({ ...customerForm, location: e.target.value })}
          required
          aria-label="Location"
        />
       <input
  placeholder="Telephone (+2507...)"
  value={customerForm.telephone}
  onChange={(e) =>
    setCustomerForm({
      ...customerForm,
      telephone: e.target.value,
    })
  }
  type="tel"
  maxLength={10}
  pattern="07[0-9]{8}"
  required
  aria-label="Telephone"
/>

        <select
          value={customerForm.ProductCode}
          onChange={(e) => onProductChange(e.target.value)}
          required
        >
          <option value="">Select Product</option>
          {products.map((p) => (
            <option key={p._id} value={p._id}>
              {p.productName}
            </option>
          ))}
        </select>

        <select
          value={customerForm.order_number}
          onChange={(e) => onOrderChange(e.target.value)}
          required
        >
          <option value="">Select Order</option>
          {orders.map((o) => (
            <option key={o._id} value={o._id}>
              {formatDateSafe(o.order_date)}
            </option>
          ))}
        </select>

        <input
          type="number"
          min="1"
          placeholder="Quantity"
          value={customerForm.quantity}
          onChange={(e) => onQuantityChange(e.target.value)}
          required
        />

        <input
          value={selectedProduct ? `Unit Price: ${selectedProduct.unitPrice}` : "Unit Price: -"}
          readOnly
        />
        <input
          value={`Total Price: ${Number(customerForm.total_price || 0).toFixed(2)}`}
          readOnly
        />

        <button type="submit">{editIds.customer ? "Update Customer" : "Add Customer"}</button>
      </form>

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

      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Location</th>
            <th>Telephone</th>
            <th>Product</th>
            <th>Qty</th>
            <th>Total</th>
            <th>Order Date</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {filteredCustomers.map((c) => (
            <tr key={c._id}>
              <td>
                {c.cust_fname} {c.cust_lname}
              </td>
              <td>{c.location}</td>
              <td>{c.telephone}</td>
              <td>{c.ProductCode?.productName || "-"}</td>
              <td>{c.quantity}</td>
              <td>{c.total_price}</td>
              <td>
                {c.order_number?.order_date ? formatDateSafe(c.order_number.order_date) : "-"}
              </td>
              <td>
                <button
                  type="button"
                  onClick={() => {
                    setCustomerForm({
                      cust_fname: c.cust_fname,
                      cust_lname: c.cust_lname,
                      location: c.location,
                      telephone: c.telephone,
                      ProductCode: c.ProductCode?._id || "",
                      order_number: c.order_number?._id || "",
                      quantity: c.quantity || 1,
                      total_price: c.total_price || 0
                    });
                    setEditIds((s) => ({ ...s, customer: c._id }));
                  }}
                >
                  Edit
                </button>
                <button
                  type="button"
                  onClick={async () => {
                    await api.del(`/customers/${c._id}`);
                    await loadData();
                  }}
                >
                  Delete
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  );
}

