import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { adminFetch } from "./adminApi";

type Rule = {
  id: string;
  name: string;
  description: string | null;
  threshold: number;
  enabled: boolean;
  sortOrder: number;
};

export default function RuleForm() {
  const { id } = useParams();
  const navigate = useNavigate();
  const isEdit = !!id;

  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [threshold, setThreshold] = useState(1);
  const [sortOrder, setSortOrder] = useState(0);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!id) return;
    adminFetch<Rule[]>("/rules").then((rules) => {
      const rule = rules.find((r) => r.id === id);
      if (rule) {
        setName(rule.name);
        setDescription(rule.description || "");
        setThreshold(rule.threshold);
        setSortOrder(rule.sortOrder);
      }
    });
  }, [id]);

  const handleSave = async () => {
    setError("");
    if (!name.trim()) {
      setError("请输入奖品名称");
      return;
    }
    setSaving(true);
    try {
      const body = {
        name: name.trim(),
        description: description.trim() || undefined,
        threshold,
        sortOrder,
      };
      if (isEdit) {
        await adminFetch(`/rules/${id}`, { method: "PUT", body: JSON.stringify(body) });
      } else {
        await adminFetch("/rules", { method: "POST", body: JSON.stringify(body) });
      }
      navigate("/admin/rules");
    } catch (e) {
      setError(e instanceof Error ? e.message : "保存失败");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="max-w-xl">
      <h2 className="text-lg font-semibold text-gray-800 mb-4">
        {isEdit ? "编辑兑换规则" : "添加兑换规则"}
      </h2>

      <div className="bg-white rounded-lg border border-gray-200 p-5 space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">奖品名称</label>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm
              focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">奖品描述</label>
          <textarea
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            rows={2}
            className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm
              focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">所需图章数</label>
          <input
            type="number"
            min={1}
            value={threshold}
            onChange={(e) => setThreshold(Number(e.target.value))}
            className="w-24 px-3 py-2 border border-gray-300 rounded-md text-sm
              focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">排序</label>
          <input
            type="number"
            value={sortOrder}
            onChange={(e) => setSortOrder(Number(e.target.value))}
            className="w-24 px-3 py-2 border border-gray-300 rounded-md text-sm
              focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
        </div>

        {error && <p className="text-sm text-red-500">{error}</p>}

        <div className="flex gap-3 pt-2">
          <button
            onClick={handleSave}
            disabled={saving}
            className="px-4 py-2 bg-blue-600 text-white text-sm rounded-md
              hover:bg-blue-700 disabled:opacity-50"
          >
            {saving ? "保存中..." : "保存"}
          </button>
          <button
            onClick={() => navigate("/admin/rules")}
            className="px-4 py-2 border border-gray-300 text-gray-600 text-sm rounded-md hover:bg-gray-50"
          >
            取消
          </button>
        </div>
      </div>
    </div>
  );
}
