import { useState, useEffect } from "react";
import { Link } 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 RuleList() {
  const [rules, setRules] = useState<Rule[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchRules = async () => {
    setLoading(true);
    try {
      const data = await adminFetch<Rule[]>("/rules");
      setRules(data);
    } finally {
      setLoading(false);
    }
  };

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

  const handleDelete = async (id: string, name: string) => {
    if (!confirm(`确定删除规则「${name}」？`)) return;
    await adminFetch(`/rules/${id}`, { method: "DELETE" });
    fetchRules();
  };

  const handleToggle = async (id: string, enabled: boolean) => {
    await adminFetch(`/rules/${id}`, {
      method: "PUT",
      body: JSON.stringify({ enabled: !enabled }),
    });
    fetchRules();
  };

  if (loading) return <p className="text-gray-500">加载中...</p>;

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-gray-800">兑换规则</h2>
        <Link
          to="/admin/rules/new"
          className="px-4 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700"
        >
          添加规则
        </Link>
      </div>

      <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="text-left px-4 py-3 font-medium text-gray-600">奖品名称</th>
              <th className="text-left px-4 py-3 font-medium text-gray-600">描述</th>
              <th className="text-center px-4 py-3 font-medium text-gray-600">所需图章</th>
              <th className="text-center px-4 py-3 font-medium text-gray-600">状态</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">操作</th>
            </tr>
          </thead>
          <tbody>
            {rules.map((rule) => (
              <tr key={rule.id} className="border-b border-gray-100 hover:bg-gray-50">
                <td className="px-4 py-3 text-gray-800">{rule.name}</td>
                <td className="px-4 py-3 text-gray-500 max-w-[250px] truncate">{rule.description || "—"}</td>
                <td className="px-4 py-3 text-center font-medium text-gray-700">{rule.threshold}</td>
                <td className="px-4 py-3 text-center">
                  <button
                    onClick={() => handleToggle(rule.id, rule.enabled)}
                    className={`px-2 py-0.5 rounded text-xs ${
                      rule.enabled ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-500"
                    }`}
                  >
                    {rule.enabled ? "启用" : "禁用"}
                  </button>
                </td>
                <td className="px-4 py-3 text-right space-x-2">
                  <Link to={`/admin/rules/${rule.id}/edit`} className="text-blue-600 hover:underline">
                    编辑
                  </Link>
                  <button onClick={() => handleDelete(rule.id, rule.name)} className="text-red-500 hover:underline">
                    删除
                  </button>
                </td>
              </tr>
            ))}
            {rules.length === 0 && (
              <tr>
                <td colSpan={5} className="px-4 py-8 text-center text-gray-400">
                  暂无规则
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
