import { useState, useEffect } from "react";
import {
  getStockMovements,
  stockIn,
  stockOut,
  getAllItems,
} from "../api/index";

const REASON_LABELS = {
  purchase: "Закупка",
  order: "Продажа",
  writeoff: "Списание",
  correction: "Корректировка",
};

export default function AdminStock() {
  const [movements, setMovements] = useState([]);
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);

  // состояние форм
  const [inForm, setInForm] = useState({
    item_id: "",
    quantity: "",
    comment: "",
  });
  const [outForm, setOutForm] = useState({
    item_id: "",
    quantity: "",
    comment: "",
  });
  const [busy, setBusy] = useState(false);

  const loadAll = () => {
    Promise.all([getStockMovements(), getAllItems()])
      .then(([movRes, itemsRes]) => {
        setMovements(movRes.data);
        setItems(itemsRes.data);
      })
      .catch(() => { })
      .finally(() => setLoading(false));
  };

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

  // приход
  const handleStockIn = async () => {
    if (!inForm.item_id || !inForm.quantity || Number(inForm.quantity) <= 0) {
      alert("Выберите товар и укажите количество");
      return;
    }
    setBusy(true);
    try {
      await stockIn({
        item_id: Number(inForm.item_id),
        quantity: Number(inForm.quantity),
        comment: inForm.comment,
      });
      setInForm({ item_id: "", quantity: "", comment: "" });
      loadAll(); // обновить историю и остатки
    } catch {
      alert("Не удалось оформить приход");
    } finally {
      setBusy(false);
    }
  };

  // уход
  const handleStockOut = async () => {
    if (
      !outForm.item_id ||
      !outForm.quantity ||
      Number(outForm.quantity) <= 0
    ) {
      alert("Выберите товар и укажите количество");
      return;
    }
    setBusy(true);
    try {
      await stockOut({
        item_id: Number(outForm.item_id),
        quantity: Number(outForm.quantity),
        comment: outForm.comment,
      });
      setOutForm({ item_id: "", quantity: "", comment: "" });
      loadAll();
    } catch (err) {
      // бэк возвращает "недостаточно товара" при нехватке
      alert(err.response?.data?.error || "Не удалось оформить списание");
    } finally {
      setBusy(false);
    }
  };

  if (loading) return <p className="text-white/60">Загрузка...</p>;

  // общий класс инпутов
  const inputClass =
    "bg-slate-800 border border-white/10 rounded px-3 py-2 text-white placeholder-white/40 focus:border-gold focus:outline-none";

  return (
    <div className="flex flex-col gap-8">
      {/* === Формы === */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Приход */}
        <div className="bg-white/5 border border-white/10 rounded-lg p-5">
          <h3 className="text-lg font-medium text-green-400 mb-4">
            Приход товара
          </h3>
          <div className="flex flex-col gap-3">
            <select
              className={inputClass}
              value={inForm.item_id}
              onChange={(e) =>
                setInForm({ ...inForm, item_id: e.target.value })
              }
            >
              <option value="">Выберите товар</option>
              {items.map((it) => (
                <option key={it.id} value={it.id}>
                  {it.name} (остаток: {it.stock} {it.unit})
                </option>
              ))}
            </select>
            <input
              type="number"
              className={inputClass}
              placeholder="Количество"
              value={inForm.quantity}
              onChange={(e) =>
                setInForm({ ...inForm, quantity: e.target.value })
              }
            />
            <input
              className={inputClass}
              placeholder="Комментарий (необязательно)"
              value={inForm.comment}
              onChange={(e) =>
                setInForm({ ...inForm, comment: e.target.value })
              }
            />
            <button
              onClick={handleStockIn}
              disabled={busy}
              className="bg-gold text-black px-6 py-2 rounded font-medium uppercase text-sm disabled:opacity-50"
            >
              Оприходовать
            </button>
          </div>
        </div>

        {/* Уход */}
        <div className="bg-white/5 border border-white/10 rounded-lg p-5">
          <h3 className="text-lg font-medium text-red-400 mb-4">
            Списание товара
          </h3>
          <div className="flex flex-col gap-3">
            <select
              className={inputClass}
              value={outForm.item_id}
              onChange={(e) =>
                setOutForm({ ...outForm, item_id: e.target.value })
              }
            >
              <option value="">Выберите товар</option>
              {items.map((it) => (
                <option key={it.id} value={it.id}>
                  {it.name} (остаток: {it.stock} {it.unit})
                </option>
              ))}
            </select>
            <input
              type="number"
              className={inputClass}
              placeholder="Количество"
              value={outForm.quantity}
              onChange={(e) =>
                setOutForm({ ...outForm, quantity: e.target.value })
              }
            />
            <input
              className={inputClass}
              placeholder="Комментарий (необязательно)"
              value={outForm.comment}
              onChange={(e) =>
                setOutForm({ ...outForm, comment: e.target.value })
              }
            />
            <button
              onClick={handleStockOut}
              disabled={busy}
              className="bg-gold text-black px-6 py-2 rounded font-medium uppercase text-sm disabled:opacity-50"
            >
              Списать
            </button>
          </div>
        </div>
      </div>

      {/* === История (твоя таблица) === */}
      <div>
        <h2 className="text-xl font-medium text-white mb-4">
          История движений
        </h2>
        {movements.length === 0 ? (
          <p className="text-white/60">Движений нет</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm text-left">
              <thead className="text-white/50 uppercase text-xs border-b border-white/10">
                <tr>
                  <th className="py-3 pr-4">Дата</th>
                  <th className="py-3 pr-4">Товар</th>
                  <th className="py-3 pr-4">Тип</th>
                  <th className="py-3 pr-4">Количество</th>
                  <th className="py-3 pr-4">Причина</th>
                  <th className="py-3 pr-4">Комментарий</th>
                </tr>
              </thead>
              <tbody>
                {movements.map((m) => (
                  <tr
                    key={m.id}
                    className="border-b border-white/5 hover:bg-white/5 transition-colors"
                  >
                    <td className="py-3 pr-4 text-white/70 whitespace-nowrap">
                      {new Date(m.created_at).toLocaleDateString("ru-RU")}
                    </td>
                    <td className="py-3 pr-4 text-white">{m.item?.name}</td>
                    <td className="py-3 pr-4">
                      <span
                        className={
                          m.type === "in" ? "text-green-400" : "text-red-400"
                        }
                      >
                        {m.type === "in" ? "Приход" : "Уход"}
                      </span>
                    </td>
                    <td className="py-3 pr-4 text-white">
                      {m.quantity} {m.item?.unit}
                    </td>
                    <td className="py-3 pr-4 text-white/70">
                      {REASON_LABELS[m.reason] || m.reason}
                    </td>
                    <td className="py-3 pr-4 text-white/50">
                      {m.comment || "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
