import React, { useEffect, useState } from "react";
import { createProduct, getProducts } from "../api/productApi";
import Layout from "../components/Layout";
import Message from "../components/Message";

const ProductPage = ({ user, setUser }) => {
  const initialForm = {
    productCode: "",
    productName: "",
    category: "",
    quantityInStock: "",
    unitPrice: "",
    supplierName: "",
    dateReceived: ""
  };
  const [formData, setFormData] = useState(initialForm);
  const [products, setProducts] = useState([]);
  const [message, setMessage] = useState("");
  const [messageType, setMessageType] = useState("");

  const loadProducts = async () => {
    const data = await getProducts();
    setProducts(data);
  };

  useEffect(() => {
    loadProducts();
  }, []);

  const handleChange = (event) => {
    setFormData({ ...formData, [event.target.name]: event.target.value });
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (Object.values(formData).some((value) => value === "")) {
      setMessageType("error");
      setMessage("All product fields are required");
      return;
    }

    try {
      const data = await createProduct(formData);
      setMessageType("success");
      setMessage(data.message);
      setFormData(initialForm);
      loadProducts();
    } catch (error) {
      setMessageType("error");
      setMessage(error.message);
    }
  };

  return (
    <Layout title="Product" user={user} setUser={setUser}>
      <form onSubmit={handleSubmit} className="rounded-md border border-primary p-4">
        <Message message={message} type={messageType} />
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          <input name="productCode" placeholder="Product Code" value={formData.productCode} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="productName" placeholder="Product Name" value={formData.productName} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="category" placeholder="Category" value={formData.category} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="quantityInStock" type="number" min="0" placeholder="Quantity In Stock" value={formData.quantityInStock} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="unitPrice" type="number" min="0" placeholder="Unit Price" value={formData.unitPrice} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="supplierName" placeholder="Supplier Name" value={formData.supplierName} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="dateReceived" type="date" value={formData.dateReceived} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
        </div>
        <button className="mt-4 rounded-md bg-primary px-5 py-3 font-semibold text-secondary">Save Product</button>
      </form>

      <div className="mt-6 overflow-x-auto">
        <table className="w-full min-w-[720px] border border-primary text-left text-sm">
          <thead className="bg-primary text-secondary">
            <tr>
              <th className="p-3">Code</th>
              <th className="p-3">Name</th>
              <th className="p-3">Category</th>
              <th className="p-3">Stock</th>
              <th className="p-3">Unit Price</th>
              <th className="p-3">Supplier</th>
            </tr>
          </thead>
          <tbody>
            {products.length === 0 ? (
              <tr className="border-t border-primary">
                <td colSpan="6" className="p-3 text-center">No products recorded</td>
              </tr>
            ) : (
              products.map((product) => (
                <tr key={product._id} className="border-t border-primary">
                  <td className="p-3">{product.productCode}</td>
                  <td className="p-3">{product.productName}</td>
                  <td className="p-3">{product.category}</td>
                  <td className="p-3">{product.quantityInStock}</td>
                  <td className="p-3">{product.unitPrice}</td>
                  <td className="p-3">{product.supplierName}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </Layout>
  );
};

export default ProductPage;
