import { useState, useEffect } from "react"
import { financeApi } from "../../api/finance"

const EMOJI_OPTIONS = ["🏠","🍔","🚗","👕","🏥","🎮","📱","✈️","🎁","🛒","🛍️","💎","📦","💰","💼","📈","🎓","🏋️","🐶","🎵","💊","🏪","☕","🍕","🎬","📚","🔧","💡","🌐","🎯"]

const fmt = (n) => n?.toLocaleString("ru-RU") + " ₽"

export default function CategoriesManager({ refreshKey }) {
  const [categories, setCategories] = useState([])
  const [tab, setTab] = useState("expense")
  const [showModal, setShowModal] = useState(false)
  const [editing, setEditing] = useState(null)
  const [loading, setLoading] = useState(true)

  // Form state
  const [emoji, setEmoji] = useState("📦")
  const [name, setName] = useState("")
  const [type, setType] = useState("expense")
  const [budget, setBudget] = useState("")
  const [showEmojiPicker, setShowEmojiPicker] = useState(false)
  const [saving, setSaving] = useState(false)
  const [deleting, setDeleting] = useState(null)

  const load = async () => {
    try {
      setLoading(true)
      const cats = await financeApi.listCategories()
      setCategories(cats)
    } catch (e) {
      console.error(e)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { load() }, [refreshKey])

  const cats = categories.filter(c => c.type === tab)

  const openAdd = () => {
    setEditing(null)
    setEmoji("📦")
    setName("")
    setType(tab)
    setBudget("")
    setShowModal(true)
  }

  const openEdit = (cat) => {
    setEditing(cat)
    setEmoji(cat.emoji || "📦")
    setName(cat.name)
    setType(cat.type)
    setBudget(cat.budget ? String(cat.budget) : "")
    setShowModal(true)
  }

  const handleSave = async () => {
    if (!name.trim()) return
    setSaving(true)
    try {
      const data = { name: name.trim(), emoji, type, budget: budget ? parseFloat(budget) : 0 }
      if (editing) {
        await financeApi.updateCategory(editing.id, data)
      } else {
        await financeApi.createCategory(data)
      }
      setShowModal(false)
      load()
    } catch (e) {
      console.error(e)
      alert("Ошибка при сохранении")
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (id) => {
    if (!confirm("Удалить категорию? Транзакции с ней останутся.")) return
    setDeleting(id)
    try {
      await financeApi.deleteCategory(id)
      load()
    } catch (e) {
      console.error(e)
      alert("Ошибка при удалении")
    } finally {
      setDeleting(null)
    }
  }

  if (loading) {
    return (
      <div className="space-y-3">
        {[1,2,3].map(i => (
          <div key={i} className="card p-4 animate-pulse">
            <div className="flex items-center gap-3">
              <div className="w-11 h-11 rounded-xl bg-gray-200 dark:bg-gray-700" />
              <div className="flex-1"><div className="h-5 bg-gray-200 dark:bg-gray-700 rounded w-1/2" /></div>
            </div>
          </div>
        ))}
      </div>
    )
  }

  return (
    <div>
      {/* Sub-tabs: expense / income */}
      <div className="flex gap-2 mb-4">
        {[["expense","Расходы"],["income","Доходы"]].map(([k,l]) => (
          <button key={k} onClick={() => setTab(k)}
            className={`px-4 py-2 rounded-xl text-sm font-semibold transition ${
              tab === k ? "bg-primary-500 text-white" : "bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
            }`}>
            {l}
          </button>
        ))}
        <div className="flex-1" />
        <button onClick={openAdd} className="px-4 py-2 bg-primary-500 text-white rounded-xl text-sm font-medium hover:bg-primary-600 transition">
          + Добавить
        </button>
      </div>

      {/* Category list */}
      <div className="space-y-3">
        {cats.length === 0 ? (
          <div className="card p-8 text-center">
            <p className="text-gray-500 dark:text-gray-400">Нет категорий</p>
            <button onClick={openAdd} className="mt-3 text-sm text-primary-600 dark:text-primary-400 font-medium">+ Добавить</button>
          </div>
        ) : cats.map(c => {
          const pct = c.budget > 0 ? Math.min(Math.round((c.spent || 0) / c.budget * 100), 100) : 0
          const isOver = c.budget > 0 && (c.spent || 0) > c.budget * 0.9
          return (
            <div key={c.id} className="card p-4">
              <div className="flex items-center gap-3">
                <div className="w-11 h-11 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center text-2xl flex-shrink-0">
                  {c.emoji}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex justify-between items-center">
                    <span className="font-medium text-gray-900 dark:text-white truncate">{c.name}</span>
                    {c.budget > 0 && (
                      <span className={`text-xs font-semibold ml-2 whitespace-nowrap ${isOver ? "text-red-500" : "text-gray-500 dark:text-gray-400"}`}>
                        {fmt(c.spent || 0)} / {fmt(c.budget)}
                      </span>
                    )}
                  </div>
                  {c.budget > 0 && (
                    <div className="mt-2 h-2 bg-gray-100 dark:bg-gray-800 rounded-full overflow-hidden">
                      <div className={`h-full rounded-full transition-all ${isOver ? "bg-red-500" : pct > 70 ? "bg-yellow-500" : "bg-primary-500"}`}
                        style={{ width: pct + "%" }} />
                    </div>
                  )}
                </div>
                <div className="flex items-center gap-1 flex-shrink-0">
                  <button onClick={() => openEdit(c)} className="p-2 text-gray-400 hover:text-primary-500 rounded-lg transition">
                    ✏️
                  </button>
                  <button onClick={() => handleDelete(c.id)} disabled={deleting === c.id}
                    className="p-2 text-gray-400 hover:text-red-500 rounded-lg transition disabled:opacity-50">
                    {deleting === c.id ? "⏳" : "🗑️"}
                  </button>
                </div>
              </div>
            </div>
          )
        })}
      </div>

      {/* Add/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black/50 flex items-end justify-center z-50" onClick={() => setShowModal(false)}>
          <div className="bg-white dark:bg-gray-900 rounded-t-3xl w-full max-w-lg p-6" onClick={e => e.stopPropagation()}>
            <div className="w-12 h-1 bg-gray-300 dark:bg-gray-700 rounded-full mx-auto mb-4" />
            <h2 className="text-lg font-display font-bold text-gray-900 dark:text-white mb-4">
              {editing ? "Редактировать категорию" : "Новая категория"}
            </h2>
            <div className="space-y-4">
              {/* Emoji + Name */}
              <div className="flex gap-3">
                <button onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                  className="w-14 h-14 rounded-xl bg-gray-100 dark:bg-gray-800 text-3xl flex items-center justify-center hover:bg-gray-200 dark:hover:bg-gray-700 transition flex-shrink-0">
                  {emoji}
                </button>
                <input value={name} onChange={e => setName(e.target.value)}
                  className="flex-1 px-4 py-3 rounded-xl bg-gray-100 dark:bg-gray-800 text-sm text-gray-900 dark:text-white outline-none"
                  placeholder="Название категории" />
              </div>

              {/* Emoji picker */}
              {showEmojiPicker && (
                <div className="grid grid-cols-8 gap-2 p-3 bg-gray-50 dark:bg-gray-800 rounded-xl">
                  {EMOJI_OPTIONS.map(e => (
                    <button key={e} onClick={() => { setEmoji(e); setShowEmojiPicker(false) }}
                      className={`text-2xl p-1 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700 transition ${emoji === e ? "bg-primary-100 dark:bg-primary-900" : ""}`}>
                      {e}
                    </button>
                  ))}
                </div>
              )}

              {/* Type toggle */}
              <div className="flex bg-gray-100 dark:bg-gray-800 rounded-xl p-1">
                {[["expense","Расход"],["income","Доход"]].map(([k,l]) => (
                  <button key={k} onClick={() => setType(k)}
                    className={`flex-1 py-2.5 rounded-lg text-sm font-semibold transition ${
                      type === k ? "bg-primary-500 text-white" : "text-gray-500"
                    }`}>
                    {l}
                  </button>
                ))}
              </div>

              {/* Budget */}
              <div>
                <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase block mb-1">Бюджет (опц.)</label>
                <div className="relative">
                  <input type="number" value={budget} onChange={e => setBudget(e.target.value)}
                    className="w-full px-4 py-3 rounded-xl bg-gray-100 dark:bg-gray-800 text-sm text-gray-900 dark:text-white outline-none"
                    placeholder="0" />
                  <span className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400">₽</span>
                </div>
              </div>

              {/* Save */}
              <button onClick={handleSave} disabled={saving || !name.trim()}
                className="w-full py-3.5 bg-primary-500 hover:bg-primary-600 disabled:opacity-50 text-white rounded-xl font-semibold transition">
                {saving ? "Сохраняю..." : editing ? "Сохранить" : "Создать"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
