import { useState, useEffect } from "react";

import {
  deleteItem,
  addItem,
  getAllItems,
  updateItem,
  uploadItemAvatar,
} from "../api/index";

function ItemFormModal({ item, onClose, onSaved }) {
  const isEdit = !!item;
  const [form, setForm] = useState({
    name: item?.name || "",
    category: item?.category || "",
    city: item?.city || "",
    price: item?.price || "",
    stock: item?.stock || "",
    unit: item?.unit || "кг",
    unit_type: item?.unit_type || "weight",
  });
  const [file, setFile] = useState(null);
  const [saving, setSaving] = useState(false);

  const handleChange = (field) => (e) =>
    setForm({ ...form, [field]: e.target.value });

  const handleSubmit = async () => {
    if (!form.name.trim()) {
      alert("Введите название товара");
      return;
    }
    if (!form.category.trim()) {
      alert("Введите категорию");
      return;
    }
    if (!form.price || Number(form.price) <= 0) {
      alert("Введите корректную цену");
      return;
    }
    if (form.stock === "" || Number(form.stock) < 0) {
      alert("Введите остаток (0 или больше)");
      return;
    }
    if (!isEdit && !file) {
      alert("Добавьте картинку товара");
      return;
    }
    setSaving(true);
    try {
      // числовые поля привести к числам
      const payload = {
        ...form,
        price: Number(form.price),
        stock: Number(form.stock),
      };

      let itemId;
      if (isEdit) {
        await updateItem(item.id, payload);
        itemId = item.id;
      } else {
        const res = await addItem(payload);
        itemId = res.data.id;
      }

      // если выбран файл — загрузить картинку
      if (file) {
        await uploadItemAvatar(itemId, file);
      }

      onSaved();
    } catch {
      alert("Не удалось сохранить товар");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
      <div className="bg-slate-800 rounded-lg p-6 w-full max-w-md max-h-[90vh] overflow-y-auto text-white">
        <h2 className="text-xl font-medium mb-4">
          {isEdit ? "Редактировать товар" : "Новый товар"}
        </h2>

        <div className="flex flex-col gap-3">
          <input
            className="bg-white/10 rounded px-3 py-2"
            placeholder="Название"
            value={form.name}
            onChange={handleChange("name")}
          />
          <input
            className="bg-white/10 rounded px-3 py-2"
            placeholder="Категория"
            value={form.category}
            onChange={handleChange("category")}
          />
          <input
            className="bg-white/10 rounded px-3 py-2"
            placeholder="Город"
            value={form.city}
            onChange={handleChange("city")}
          />
          <input
            type="number"
            className="bg-white/10 rounded px-3 py-2"
            placeholder="Цена"
            value={form.price}
            onChange={handleChange("price")}
          />
          <input
            type="number"
            className="bg-white/10 rounded px-3 py-2"
            placeholder="Остаток"
            value={form.stock}
            onChange={handleChange("stock")}
          />
          <input
            className="bg-white/10 rounded px-3 py-2"
            placeholder="Единица (кг, шт)"
            value={form.unit}
            onChange={handleChange("unit")}
          />
          <select
            className="bg-white/10 rounded px-3 py-2"
            value={form.unit_type}
            onChange={handleChange("unit_type")}
          >
            <option value="weight">На вес</option>
            <option value="piece">Поштучно</option>
          </select>

          {/* картинка */}
          <div>
            <label className="text-white/50 text-sm block mb-1">Картинка</label>
            <input
              type="file"
              accept="image/*"
              onChange={(e) => setFile(e.target.files[0])}
              className="text-sm text-white/70"
            />
          </div>
        </div>

        <div className="flex gap-3 mt-6">
          <button
            onClick={handleSubmit}
            disabled={saving}
            className="bg-gold text-black px-6 py-2 rounded font-medium grow disabled:opacity-50"
          >
            {saving ? "Сохранение..." : isEdit ? "Сохранить" : "Создать"}
          </button>
          <button onClick={onClose} className="bg-white/10 px-6 py-2 rounded">
            Отмена
          </button>
        </div>
      </div>
    </div>
  );
}

// ===== Основной компонент =====
export default function AdminItems() {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingItem, setEditingItem] = useState(null);

  const loadItems = () => {
    getAllItems()
      .then((res) => {
        setItems(res.data);
      })
      .catch(() => { })
      .finally(() => setLoading(false));
  };

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

  const handleDelete = async (id, name) => {
    if (!confirm(`Удалить товар "${name}"?`)) return;
    try {
      await deleteItem(id);
      setItems((prev) => prev.filter((it) => it.id !== id));
    } catch {
      alert("Не удалось удалить товар");
    }
  };

  const openCreate = () => {
    setEditingItem(null);
    setShowModal(true);
  };
  const openEdit = (item) => {
    setEditingItem(item);
    setShowModal(true);
  };
  const handleSaved = () => {
    setShowModal(false);
    loadItems();
  };

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

  return (
    <div>
      <button
        onClick={openCreate}
        className="mb-6 bg-gold text-black px-6 py-2 rounded-md font-medium uppercase text-sm"
      >
        + Добавить товар
      </button>

      <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>
              <th className="py-3 pr-4">Действия</th>
            </tr>
          </thead>
          <tbody>
            {items.map((item) => (
              <tr
                key={item.id}
                className="border-b border-white/5 hover:bg-white/5 transition-colors"
              >
                <td className="py-3 pr-4">
                  <img
                    src={item.avatar_url}
                    alt=""
                    className="w-12 h-12 object-cover rounded"
                  />
                </td>
                <td className="py-3 pr-4 font-medium">{item.name}</td>
                <td className="py-3 pr-4 text-white/70">{item.category}</td>
                <td className="py-3 pr-4">{item.price} ₽</td>
                <td className="py-3 pr-4">
                  {item.stock} {item.unit}
                </td>
                <td className="py-3 pr-4 text-white/70">
                  {item.unit_type === "piece" ? "шт" : "вес"}
                </td>
                <td className="py-3 pr-4">
                  <div className="flex gap-2">
                    <button
                      onClick={() => openEdit(item)}
                      className="text-blue-400 hover:text-blue-300 text-sm"
                    >
                      Изменить
                    </button>
                    <button
                      onClick={() => handleDelete(item.id, item.name)}
                      className="text-red-400 hover:text-red-300 text-sm"
                    >
                      Удалить
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showModal && (
        <ItemFormModal
          item={editingItem}
          onClose={() => setShowModal(false)}
          onSaved={handleSaved}
        />
      )}
    </div>
  );
}
