import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  getSourceCategories,
  createSourceCategory,
  updateSourceCategory,
  deleteSourceCategory,
  type SourceCategory,
} from "../../lib/commands";
import { useUIStore } from "../../store/ui";

interface Props {
  onClose: () => void;
}

export function CategoryManager({ onClose }: Props) {
  const [newName, setNewName] = useState("");
  const [newIcon, setNewIcon] = useState("");
  const [newColor, setNewColor] = useState("#6B7280");
  const [editTarget, setEditTarget] = useState<SourceCategory | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<SourceCategory | null>(null);

  const qc = useQueryClient();
  const showToast = useUIStore((s) => s.showToast);

  const { data: categories = [] } = useQuery({
    queryKey: ["source_categories"],
    queryFn: getSourceCategories,
  });

  const handleCreate = async () => {
    if (!newName.trim()) return;
    try {
      await createSourceCategory(newName.trim(), newIcon || undefined, newColor);
      qc.invalidateQueries({ queryKey: ["source_categories"] });
      setNewName("");
      setNewIcon("");
      setNewColor("#6B7280");
      showToast("分类已创建");
    } catch (e) {
      showToast(`创建失败: ${e}`);
    }
  };

  const handleUpdate = async () => {
    if (!editTarget || !editTarget.name.trim()) return;
    try {
      await updateSourceCategory(editTarget.id, editTarget.name, editTarget.icon, editTarget.color);
      qc.invalidateQueries({ queryKey: ["source_categories"] });
      setEditTarget(null);
      showToast("已更新");
    } catch (e) {
      showToast(`更新失败: ${e}`);
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await deleteSourceCategory(deleteTarget.id);
      qc.invalidateQueries({ queryKey: ["source_categories"] });
      setDeleteTarget(null);
      showToast("已删除");
    } catch (e) {
      showToast(`删除失败: ${e}`);
    }
  };

  const presetColors = ["#EF4444", "#F97316", "#EAB308", "#22C55E", "#3B82F6", "#8B5CF6", "#EC4899", "#6B7280"];

  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl shadow-2xl w-[420px] max-h-[75vh] overflow-y-auto p-6 space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="text-base font-semibold text-gray-800">管理分类</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl leading-none">&times;</button>
        </div>

        {/* 新增分类 */}
        <div className="border border-dashed border-gray-300 rounded-lg p-3 space-y-2">
          <div className="flex gap-2">
            <input
              value={newIcon}
              onChange={(e) => setNewIcon(e.target.value)}
              placeholder="图标"
              className="w-14 border border-gray-200 rounded-md px-2 py-1.5 text-sm text-center outline-none focus:ring-2 focus:ring-emerald-200"
            />
            <input
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              placeholder="分类名称"
              className="flex-1 border border-gray-200 rounded-md px-3 py-1.5 text-sm outline-none focus:ring-2 focus:ring-emerald-200"
              onKeyDown={(e) => e.key === "Enter" && handleCreate()}
            />
            <button
              onClick={handleCreate}
              disabled={!newName.trim()}
              className="px-3 py-1.5 text-sm bg-emerald-600 text-white rounded-md hover:bg-emerald-700 disabled:opacity-50"
            >
              添加
            </button>
          </div>
          <div className="flex items-center gap-1.5">
            <span className="text-xs text-gray-400">色标:</span>
            {presetColors.map((c) => (
              <button
                key={c}
                onClick={() => setNewColor(c)}
                className={`w-5 h-5 rounded-full border-2 transition-all ${newColor === c ? "border-gray-800 scale-110" : "border-transparent"}`}
                style={{ backgroundColor: c }}
              />
            ))}
          </div>
        </div>

        {/* 分类列表 */}
        <div className="space-y-1">
          {categories.length === 0 && (
            <p className="text-sm text-gray-400 text-center py-4">暂无分类</p>
          )}
          {categories.map((cat) => (
            <div key={cat.id} className="flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-gray-50 group">
              {editTarget?.id === cat.id ? (
                <>
                  <input
                    value={editTarget.icon}
                    onChange={(e) => setEditTarget({ ...editTarget, icon: e.target.value })}
                    className="w-10 border border-gray-200 rounded px-1 py-1 text-sm text-center outline-none"
                  />
                  <input
                    value={editTarget.name}
                    onChange={(e) => setEditTarget({ ...editTarget, name: e.target.value })}
                    className="flex-1 border border-gray-200 rounded px-2 py-1 text-sm outline-none"
                    onKeyDown={(e) => e.key === "Enter" && handleUpdate()}
                  />
                  <input
                    type="color"
                    value={editTarget.color}
                    onChange={(e) => setEditTarget({ ...editTarget, color: e.target.value })}
                    className="w-6 h-6 rounded border-0 cursor-pointer"
                  />
                  <button onClick={handleUpdate} className="text-xs text-emerald-600 hover:underline">保存</button>
                  <button onClick={() => setEditTarget(null)} className="text-xs text-gray-400 hover:underline">取消</button>
                </>
              ) : (
                <>
                  <span
                    className="w-3 h-3 rounded-full shrink-0"
                    style={{ backgroundColor: cat.color }}
                  />
                  <span className="text-sm mr-1">{cat.icon}</span>
                  <span className="flex-1 text-sm text-gray-700">{cat.name}</span>
                  <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button
                      onClick={() => setEditTarget({ ...cat })}
                      className="text-xs text-blue-500 hover:underline"
                    >
                      编辑
                    </button>
                    <button
                      onClick={() => setDeleteTarget(cat)}
                      className="text-xs text-red-500 hover:underline"
                    >
                      删除
                    </button>
                  </div>
                </>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* 删除确认 */}
      {deleteTarget && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[60]">
          <div className="bg-white rounded-xl shadow-2xl w-72 p-5 space-y-3">
            <p className="text-sm text-gray-700">
              删除分类「{deleteTarget.name}」？已归类的项目不会被删除。
            </p>
            <div className="flex justify-end gap-2">
              <button onClick={() => setDeleteTarget(null)} className="px-3 py-1.5 text-xs border border-gray-200 rounded-md text-gray-600 hover:bg-gray-50">取消</button>
              <button onClick={handleDelete} className="px-3 py-1.5 text-xs bg-red-600 text-white rounded-md hover:bg-red-700">删除</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
