import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { getTags, createTag, updateTag, deleteTag, type ProjectTag } from "../../lib/commands";
import { useUIStore } from "../../store/ui";

const PRESET_COLORS = [
  "#8b5cf6", "#3b82f6", "#10b981", "#f59e0b",
  "#ef4444", "#ec4899", "#06b6d4", "#84cc16",
  "#f97316", "#6366f1",
];

export function TagsManager() {
  const showToast = useUIStore((s) => s.showToast);
  const qc = useQueryClient();
  const { data: tags = [] } = useQuery({ queryKey: ["tags"], queryFn: getTags });

  const [newName, setNewName] = useState("");
  const [newColor, setNewColor] = useState(PRESET_COLORS[0]);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editName, setEditName] = useState("");
  const [editColor, setEditColor] = useState("");

  const handleCreate = async () => {
    if (!newName.trim()) return;
    try {
      await createTag(newName.trim(), newColor);
      qc.invalidateQueries({ queryKey: ["tags"] });
      setNewName("");
    } catch (e) {
      showToast(`❌ ${e}`);
    }
  };

  const startEdit = (tag: ProjectTag) => {
    setEditingId(tag.id);
    setEditName(tag.name);
    setEditColor(tag.color);
  };

  const handleUpdate = async () => {
    if (!editingId || !editName.trim()) return;
    try {
      await updateTag(editingId, editName.trim(), editColor);
      qc.invalidateQueries({ queryKey: ["tags"] });
      setEditingId(null);
    } catch (e) {
      showToast(`❌ ${e}`);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteTag(id);
      qc.invalidateQueries({ queryKey: ["tags"] });
      showToast("已删除");
    } catch (e) {
      showToast(`❌ ${e}`);
    }
  };

  return (
    <div className="space-y-6">
      {/* 新建标签 */}
      <div>
        <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">新建标签</h3>
        <div className="flex items-center gap-3 p-4 bg-white rounded-xl border border-gray-200">
          <input
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleCreate()}
            placeholder="标签名称"
            className="flex-1 border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-violet-200"
          />
          {/* 颜色选择 */}
          <div className="flex gap-1.5 flex-wrap">
            {PRESET_COLORS.map((c) => (
              <button
                key={c}
                onClick={() => setNewColor(c)}
                className={`w-5 h-5 rounded-full border-2 transition-transform ${newColor === c ? "border-gray-600 scale-110" : "border-transparent"}`}
                style={{ backgroundColor: c }}
              />
            ))}
          </div>
          {/* 预览 */}
          <span
            className="px-2.5 py-1 rounded-full text-xs font-medium text-white shrink-0"
            style={{ backgroundColor: newColor }}
          >
            {newName || "预览"}
          </span>
          <button
            onClick={handleCreate}
            disabled={!newName.trim()}
            className="px-3 py-2 rounded-lg bg-violet-600 text-white text-sm hover:bg-violet-700 disabled:opacity-40 shrink-0"
          >
            创建
          </button>
        </div>
      </div>

      {/* 标签列表 */}
      <div>
        <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">
          已有标签 <span className="text-gray-300 font-normal ml-1">({tags.length})</span>
        </h3>
        {tags.length === 0 ? (
          <p className="text-sm text-gray-400 text-center py-8">还没有标签，在上方新建</p>
        ) : (
          <div className="space-y-2">
            {tags.map((tag) => (
              <div key={tag.id} className="flex items-center gap-3 px-4 py-3 bg-white rounded-xl border border-gray-200">
                {editingId === tag.id ? (
                  <>
                    <input
                      value={editName}
                      onChange={(e) => setEditName(e.target.value)}
                      onKeyDown={(e) => e.key === "Enter" && handleUpdate()}
                      className="flex-1 border border-gray-200 rounded-lg px-3 py-1.5 text-sm outline-none focus:ring-2 focus:ring-violet-200"
                      autoFocus
                    />
                    <div className="flex gap-1.5">
                      {PRESET_COLORS.map((c) => (
                        <button
                          key={c}
                          onClick={() => setEditColor(c)}
                          className={`w-5 h-5 rounded-full border-2 transition-transform ${editColor === c ? "border-gray-600 scale-110" : "border-transparent"}`}
                          style={{ backgroundColor: c }}
                        />
                      ))}
                    </div>
                    <span
                      className="px-2.5 py-1 rounded-full text-xs font-medium text-white shrink-0"
                      style={{ backgroundColor: editColor }}
                    >
                      {editName || "预览"}
                    </span>
                    <button onClick={handleUpdate} className="px-3 py-1.5 rounded-lg bg-violet-600 text-white text-xs hover:bg-violet-700 shrink-0">保存</button>
                    <button onClick={() => setEditingId(null)} className="px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 text-xs hover:bg-gray-50 shrink-0">取消</button>
                  </>
                ) : (
                  <>
                    <span
                      className="px-2.5 py-1 rounded-full text-xs font-medium text-white"
                      style={{ backgroundColor: tag.color }}
                    >
                      {tag.name}
                    </span>
                    <span className="text-xs text-gray-300 font-mono">{tag.color}</span>
                    <div className="ml-auto flex gap-2">
                      <button onClick={() => startEdit(tag)} className="text-xs text-gray-400 hover:text-gray-700 px-2 py-1 rounded hover:bg-gray-50">编辑</button>
                      <button onClick={() => handleDelete(tag.id)} className="text-xs text-red-400 hover:text-red-600 px-2 py-1 rounded hover:bg-red-50">删除</button>
                    </div>
                  </>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
