import { useState, useEffect } from "react";
import Modal from "./Modal";
import { adminFetch } from "./adminApi";
import { useToast } from "./Toast";
import { Field, ErrorRow, FormFooter, fieldCls } from "./FormPrimitives";

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

type Props = {
  open: boolean;
  id: string | null;
  onClose: () => void;
  onSaved: () => void;
};

export default function RuleForm({ open, id, onClose, onSaved }: Props) {
  const toast = useToast();
  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("");

  const isEdit = !!id;

  useEffect(() => {
    if (!open) return;
    setError("");
    if (!id) {
      setName(""); setDescription(""); setThreshold(1); setSortOrder(0);
      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);
      }
    });
  }, [open, id]);

  const handleSave = async () => {
    setError("");
    if (!name.trim()) return setError("请输入奖品名称");
    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) });
      }
      toast.show("已保存");
      onSaved();
      onClose();
    } catch (e) {
      setError(e instanceof Error ? e.message : "保存失败");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      size="md"
      eyebrow={isEdit ? "Edit Rule" : "New Rule"}
      title={isEdit ? "编辑兑换规则" : "添加兑换规则"}
    >
      <div className="px-7 py-6 space-y-5">
        <Field label="奖品名称" required>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="如：城市限定明信片"
            className={fieldCls}
          />
        </Field>

        <Field label="奖品描述">
          <textarea
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            rows={3}
            placeholder="选填"
            className={fieldCls + " resize-none"}
          />
        </Field>

        <div className="grid grid-cols-2 gap-5">
          <Field label="所需图章数" required hint="≥ 1">
            <input
              type="number"
              min={1}
              value={threshold}
              onChange={(e) => setThreshold(Number(e.target.value))}
              className={fieldCls + " w-full"}
            />
          </Field>
          <Field label="排序" hint="数字小的在前">
            <input
              type="number"
              value={sortOrder}
              onChange={(e) => setSortOrder(Number(e.target.value))}
              className={fieldCls + " w-full"}
            />
          </Field>
        </div>

        {error && <ErrorRow text={error} />}
      </div>

      <FormFooter onCancel={onClose} onSave={handleSave} saving={saving} primaryLabel={isEdit ? "保存" : "创建"} />
    </Modal>
  );
}
