import { useState, useEffect } from "react";
import { adminFetch } from "./adminApi";
import { useToast } from "./Toast";
import RuleForm from "./RuleForm";
import PageHeader, {
  PrimaryButton,
  StatusChip,
  ActionButton,
  EmptyState,
  LoadingBlock,
  IconEdit,
  IconDelete,
} from "./PageHeader";
import { TableCard, TableHeadRow } from "./StampList";

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

export default function RuleList() {
  const toast = useToast();
  const [rules, setRules] = useState<Rule[]>([]);
  const [loading, setLoading] = useState(true);
  const [formState, setFormState] = useState<{ open: boolean; id: string | null }>({ open: false, id: null });

  const fetchRules = async () => {
    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;
    try {
      await adminFetch(`/rules/${id}`, { method: "DELETE" });
      toast.show("已删除");
      fetchRules();
    } catch (e) {
      toast.show(e instanceof Error ? e.message : "删除失败", "error");
    }
  };

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

  return (
    <>
      <PageHeader
        eyebrow="05 · Rules"
        title="兑换规则"
        caption="设置可兑换的奖品与所需图章数"
        action={<PrimaryButton onClick={() => setFormState({ open: true, id: null })}>添加规则</PrimaryButton>}
      />

      {loading ? (
        <LoadingBlock />
      ) : (
        <TableCard>
          {rules.length === 0 ? (
            <EmptyState
              message="尚未创建兑换规则"
              action={
                <PrimaryButton onClick={() => setFormState({ open: true, id: null })}>
                  添加第一条规则
                </PrimaryButton>
              }
            />
          ) : (
            <table className="w-full">
              <thead>
                <TableHeadRow cols={["奖品", "描述", "所需图章", "状态", "操作"]} />
              </thead>
              <tbody>
                {rules.map((rule, i) => (
                  <tr
                    key={rule.id}
                    className="border-t border-[var(--border-muted)] hover:bg-white/60 transition-colors animate-admin-row"
                    style={{ animationDelay: `${Math.min(i, 12) * 0.03}s` }}
                  >
                    <td className="px-5 py-4">
                      <p className="text-[15px] font-medium text-[var(--text-primary)]">{rule.name}</p>
                    </td>
                    <td className="px-5 py-4">
                      <p className="text-sm text-[var(--text-muted)] max-w-[340px] truncate">
                        {rule.description || "—"}
                      </p>
                    </td>
                    <td className="px-5 py-4 text-center w-[140px]">
                      <div className="inline-flex items-baseline gap-1.5">
                        <span
                          className="text-2xl text-[var(--terracotta)] leading-none"
                          style={{ fontFamily: "'Playfair Display', serif", fontWeight: 600 }}
                        >
                          {rule.threshold}
                        </span>
                        <span className="text-[10px] tracking-[0.2em] uppercase text-[var(--text-muted)]">
                          枚
                        </span>
                      </div>
                    </td>
                    <td className="px-5 py-4 text-center w-[110px]">
                      <StatusChip enabled={rule.enabled} onClick={() => handleToggle(rule.id, rule.enabled)} />
                    </td>
                    <td className="px-5 py-4 w-[140px]">
                      <div className="flex items-center justify-end gap-1">
                        <ActionButton title="编辑" onClick={() => setFormState({ open: true, id: rule.id })}>
                          {IconEdit}
                        </ActionButton>
                        <ActionButton
                          title="删除"
                          variant="danger"
                          onClick={() => handleDelete(rule.id, rule.name)}
                        >
                          {IconDelete}
                        </ActionButton>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </TableCard>
      )}

      <RuleForm
        open={formState.open}
        id={formState.id}
        onClose={() => setFormState({ open: false, id: null })}
        onSaved={fetchRules}
      />
    </>
  );
}
