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

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

  const [form, setForm] = useState({
    sparePart_id: "",
    stockOutQuantity: "",
    stockOutUnitPrice: ""
  });
   
  const [editingId, setEditingId] = useState(null);

  // LOAD DATA
  const loadData = async () => {
    try {
      const partsRes = await API.get("/spareparts");
      const stockOutRes = await API.get("/stockout");

      setParts(partsRes.data);
      setStockOuts(stockOutRes.data);
    } catch {
      setError("Failed to load data");
    }
  };

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

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

    if (!form.sparePart_id || !form.stockOutQuantity || !form.stockOutUnitPrice) {
      setError("All fields are required");
      return;
    }

    try {
      if (editingId) {
        await API.put(`/stockout/${editingId}`, form);
      } else {
        await API.post("/stockout", form);
      }

      setForm({
        sparePart_id: "",
        stockOutQuantity: "",
        stockOutUnitPrice: ""
      });

      setEditingId(null);
      loadData();

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

  // DELETE
  const handleDelete = async (id) => {
    if (!confirm("Delete this record?")) return;

    await API.delete(`/stockout/${id}`);
    loadData();
  };

  // EDIT
  const handleEdit = (item) => {
    setForm({
      sparePart_id: item.sparePart_id?._id,
      stockOutQuantity: item.stockOutQuantity,
      stockOutUnitPrice: item.stockOutUnitPrice
    });

    setEditingId(item._id);
  };

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

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

      {/* FORM */}
      <div className="bg-white p-4 rounded shadow mb-6 max-w-md space-y-3">

        <select
          className="border p-2 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
          type="number"
          placeholder="Quantity"
          className="border p-2 w-full rounded"
          value={form.stockOutQuantity}
          onChange={(e) =>
            setForm({ ...form, stockOutQuantity: e.target.value })
          }
        />

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

        <button
          onClick={submit}
          className={`w-full text-white p-2 rounded ${
            editingId ? "bg-yellow-600" : "bg-red-600"
          }`}
        >
          {editingId ? "Update StockOut" : "Add StockOut"}
        </button>
      </div>

      {/* TABLE */}
      <div className="bg-white p-4 rounded shadow">
        <h3 className="font-semibold mb-3">Stock Out Records</h3>

        <table className="w-full text-sm">
          <thead>
            <tr className="border-b text-left">
              <th>Product</th>
              <th>Qty</th>
              <th>Unit Price</th>
              <th>Total</th>
              <th>Date</th>
              <th>Actions</th>
            </tr>
          </thead>

          <tbody>
            {stockOuts.map((s) => (
              <tr key={s._id} className="border-b">
                <td>{s.sparePart_id?.name}</td>
                <td>{s.stockOutQuantity}</td>
                <td>{s.stockOutUnitPrice}</td>
                <td className="font-semibold">
                  {s.stockOutTotalPrice}
                </td>
                <td>
                  {new Date(s.stockOutDate).toLocaleDateString()}
                </td>

                <td className="space-x-2">
                  <button
                    onClick={() => handleEdit(s)}
                    className="bg-yellow-500 text-white px-2 py-1 rounded text-xs"
                  >
                    Edit
                  </button>

                  <button
                    onClick={() => handleDelete(s._id)}
                    className="bg-red-600 text-white px-2 py-1 rounded text-xs"
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}