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

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

  const [form, setForm] = useState({
    SparePart_id: "",
    StockInQuantity: ""
  });

  // LOAD PRODUCTS
  useEffect(() => {
    API.get("/spareparts")
      .then(res => setParts(res.data))
      .catch(() => setError("Failed to load products"));
  }, []);

  // SUBMIT
  const submit = async () => {
    setError("");

    if (!form.SparePart_id || !form.StockInQuantity) {
      setError("Please fill all fields");
      return;
    }

    try {
      await API.post("/stockin", form);
      alert("Stock In saved");

      // reset form
      setForm({
        SparePart_id: "",
        StockInQuantity: ""
      });

    } catch (err) {
      setError(err.response?.data?.message || "Error saving stock in");
    }
  };

  return (
    <div className="max-w-md">
      <h2 className="font-bold mb-4 text-lg">Stock In</h2>

      {/* ERROR */}
      {error && (
        <div className="bg-red-100 text-red-700 p-2 rounded mb-3 text-sm">
          {error}
        </div>
      )}

      {/* SELECT PRODUCT */}
      <select
        className="border p-2 mb-3 w-full rounded"
        value={form.SparePart_id}
        onChange={(e) =>
          setForm({ ...form, SparePart_id: e.target.value })
        }
      >
        <option value="">Select product</option>
        {parts.map((p) => (
          <option key={p._id} value={p._id}>
            {p.name}
          </option>
        ))}
      </select>

      {/* INPUT FIXED */}
      <input
        type="number"
        className="border p-2 block mb-3 w-full rounded"
        placeholder="Quantity"
        value={form.StockInQuantity}
        onChange={(e) =>
          setForm({ ...form, StockInQuantity: e.target.value })
        }
      />

      {/* BUTTON */}
      <button
        className="bg-blue-700 text-white p-2 rounded w-full hover:bg-blue-600"
        onClick={submit}
      >
        Save
      </button>
    </div>
  );
}