import { useEffect, useState } from "react";
import API from "../services/api";

export default function SpareParts() {
  const [parts, setParts] = useState([]);
  const [error, setError] = useState("");

  const [form, setForm] = useState({
    name: "",
    category: "",
    quantity: "",
    unitPrice: ""
  });

  // LOAD DATA
  const loadParts = async () => {
    try {
      const res = await API.get("/spareparts");
      setParts(res.data);
    } catch (err) {
      setError("Failed to load data");
    }
  };

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

  // HANDLE SUBMIT
  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");

    if (!form.name || !form.category) {
      setError("Name and category are required");
      return;
    }

    const totalPrice = form.quantity * form.unitPrice;

    try {
      await API.post("/spareparts", {
        ...form,
        totalPrice
      });

      // RESET
      setForm({
        name: "",
        category: "",
        quantity: "",
        unitPrice: ""
      });

      loadParts();

    } catch (err) {
      setError(err.response?.data?.message || "Error adding spare part");
    }
  };

  return (
    <div>
      <h2 className="text-xl font-bold mb-4">Spare Parts</h2>

      {/* FORM */}
      <form
        onSubmit={handleSubmit}
        className="bg-white p-5 rounded shadow mb-6 max-w-lg space-y-3"
      >
        {error && (
          <div className="bg-red-100 text-red-700 p-2 rounded text-sm">
            {error}
          </div>
        )}

        <input
          type="text"
          placeholder="Product Name"
          value={form.name}
          onChange={(e) =>
            setForm({ ...form, name: e.target.value })
          }
          className="w-full border p-2 rounded"
        />

        <input
          type="text"
          placeholder="Category"
          value={form.category}
          onChange={(e) =>
            setForm({ ...form, category: e.target.value })
          }
          className="w-full border p-2 rounded"
        />

        <input
          type="number"
          placeholder="Quantity"
          value={form.quantity}
          onChange={(e) =>
            setForm({ ...form, quantity: e.target.value })
          }
          className="w-full border p-2 rounded"
        />

        <input
          type="number"
          placeholder="Unit Price"
          value={form.unitPrice}
          onChange={(e) =>
            setForm({ ...form, unitPrice: e.target.value })
          }
          className="w-full border p-2 rounded"
        />

        <button className="bg-blue-700 text-white px-4 py-2 rounded w-full hover:bg-blue-600">
          Add Spare Part
        </button>
      </form>

      {/* TABLE */}
      <div className="bg-white p-5 rounded shadow">
        <h3 className="font-semibold mb-3">All Spare Parts</h3>

        <table className="w-full text-sm">
          <thead>
            <tr className="border-b text-left">
              <th>Name</th>
              <th>Category</th>
              <th>Quantity</th>
              <th>Unit Price</th>
              <th>Total Price</th>
            </tr>
          </thead>

          <tbody>
            {parts.map((p) => (
              <tr key={p._id} className="border-b">
                <td>{p.name}</td>
                <td>{p.category}</td>
                <td>{p.quantity}</td>
                <td>{p.unitPrice}</td>
                <td className="font-semibold text-blue-700">
                  {p.totalPrice}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}