import { useCallback, useEffect, useMemo, useState } from "react"
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  DeleteOutlined,
  EditOutlined,
  GiftOutlined,
  PercentageOutlined,
  PlusOutlined,
  ReloadOutlined,
  TagOutlined,
} from "@ant-design/icons"
import {
  Button,
  Card,
  Col,
  Empty,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Space,
  Statistic,
  Switch,
  Table,
  Tag,
  Typography,
  message,
  type TableColumnsType,
} from "antd"
import {
  createPromoCode,
  deletePromoCode,
  listPromoCodes,
  updatePromoCode,
  type AdminPromoCode,
  type AdminPromoCodePayload,
  type PromoCodeDiscountLevel,
  type PromoCodeScope,
  type PromoCodeType,
} from "../api/promo_code"
import { listProducts, type Product } from "../api/product"
import { listCategories, listGroups, type ProductCategory, type ProductGroup } from "../api/product_catalog"

const { Paragraph, Text, Title } = Typography

const CYCLE_OPTIONS = [
  { label: "按小时", value: "hourly" },
  { label: "按天", value: "daily" },
  { label: "月付", value: "monthly" },
  { label: "季付", value: "quarterly" },
  { label: "半年付", value: "semi_annually" },
  { label: "年付", value: "annually" },
  { label: "两年付", value: "biennially" },
  { label: "三年付", value: "triennially" },
  { label: "一次性", value: "one_time" },
]

const TYPE_META: Record<PromoCodeType, { label: string; color: string }> = {
  percent: { label: "百分比", color: "blue" },
  fixed: { label: "固定金额", color: "green" },
  override: { label: "覆盖价格", color: "orange" },
}

const LEVEL_META: Record<PromoCodeDiscountLevel, { label: string; color: string }> = {
  order: { label: "订单级", color: "purple" },
  product: { label: "产品级", color: "cyan" },
}

const SCOPE_META: Record<PromoCodeScope, { label: string }> = {
  all: { label: "全场" },
  category: { label: "指定分类" },
  group: { label: "指定产品组" },
  product: { label: "指定产品" },
}

function typeMeta(value: string | null | undefined) {
  return TYPE_META[value as PromoCodeType] ?? { label: value || "未知类型", color: "default" }
}

function levelMeta(value: string | null | undefined) {
  return LEVEL_META[value as PromoCodeDiscountLevel] ?? { label: value || "未知层级", color: "default" }
}

function scopeLabel(value: string | null | undefined) {
  return SCOPE_META[value as PromoCodeScope]?.label ?? value ?? "未知范围"
}

interface PromoFormValues {
  code: string
  description?: string | null
  type: PromoCodeType
  discount_level: PromoCodeDiscountLevel
  value: number
  scope: PromoCodeScope
  scope_ids?: number[]
  starts_at?: string | null
  expires_at?: string | null
  max_uses: number
  max_uses_per_user: number
  applicable_cycles?: string[]
  min_order_amount: number
  min_quantity: number
  max_discount_amount: number
  required_product_ids?: number[]
  required_group_ids?: number[]
  required_category_ids?: number[]
  allowed_user_ids?: Array<number | string>
  new_users_only: boolean
  applies_to_renewals: boolean
  is_stackable: boolean
  is_enabled: boolean
}

function centsToYuan(cents: number) {
  return (Number(cents || 0) / 100).toFixed(2)
}

function formatValue(record: AdminPromoCode) {
  if (record.type === "percent") return `${record.value}%`
  if (record.type === "fixed") return `¥${centsToYuan(record.value)}`
  return `覆盖到 ¥${centsToYuan(record.value)}`
}

function displayFormValue(record: AdminPromoCode) {
  return record.type === "percent" ? record.value : record.value / 100
}

function backendValue(type: PromoCodeType, value: number) {
  return type === "percent" ? Math.round(value || 0) : Math.round((value || 0) * 100)
}

function toLocalInput(value: string | null | undefined) {
  if (!value) return undefined
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return undefined
  const pad = (n: number) => String(n).padStart(2, "0")
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`
}

function toIso(value: string | null | undefined) {
  if (!value) return null
  const date = new Date(value)
  return Number.isNaN(date.getTime()) ? null : date.toISOString()
}

function normalizeIds(values?: Array<number | string> | null) {
  return (values ?? [])
    .map((value) => Number(value))
    .filter((value) => Number.isInteger(value) && value > 0)
}

function generateCouponCode() {
  const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
  let suffix = ""
  for (let i = 0; i < 8; i += 1) {
    suffix += alphabet[Math.floor(Math.random() * alphabet.length)]
  }
  return `QY${suffix}`
}

function formatDate(value: string | null | undefined) {
  if (!value) return "-"
  return new Date(value).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  })
}

export default function AdminPromoCodes() {
  const [items, setItems] = useState<AdminPromoCode[]>([])
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [modalOpen, setModalOpen] = useState(false)
  const [editing, setEditing] = useState<AdminPromoCode | null>(null)
  const [products, setProducts] = useState<Product[]>([])
  const [groups, setGroups] = useState<ProductGroup[]>([])
  const [categories, setCategories] = useState<ProductCategory[]>([])
  const [keyword, setKeyword] = useState("")
  const [levelFilter, setLevelFilter] = useState<PromoCodeDiscountLevel | "all">("all")
  const [enabledFilter, setEnabledFilter] = useState<boolean | "all">("all")
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  const [total, setTotal] = useState(0)
  const [form] = Form.useForm<PromoFormValues>()

  const couponType = Form.useWatch("type", form) as PromoCodeType | undefined
  const scope = Form.useWatch("scope", form) as PromoCodeScope | undefined

  const loadOptions = useCallback(async () => {
    try {
      const [productRes, groupRes, categoryRes] = await Promise.all([
        listProducts(),
        listGroups(undefined, { includeOsOptions: false }),
        listCategories(),
      ])
      setProducts(productRes.data ?? [])
      setGroups(groupRes.data ?? [])
      setCategories(categoryRes.data ?? [])
    } catch {
      message.warning("适用范围选项加载失败，可稍后刷新")
    }
  }, [])

  const reload = useCallback(async () => {
    setLoading(true)
    try {
      const res = await listPromoCodes({
        keyword,
        discount_level: levelFilter,
        enabled: enabledFilter,
        offset: (page - 1) * pageSize,
        limit: pageSize,
      })
      setItems(res.data?.items ?? [])
      setTotal(res.data?.total ?? 0)
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "加载优惠券失败")
    } finally {
      setLoading(false)
    }
  }, [enabledFilter, keyword, levelFilter, page, pageSize])

  useEffect(() => {
    void loadOptions()
  }, [loadOptions])

  useEffect(() => {
    void reload()
  }, [reload])

  const stats = useMemo(() => {
    const enabled = items.filter((item) => item.is_enabled).length
    const productLevel = items.filter((item) => item.discount_level === "product").length
    return { total, enabled, disabled: items.length - enabled, productLevel }
  }, [items, total])

  const productOptions = useMemo(() => (
    products.map((item) => ({
        label: `${item.name} (${item.sku})`,
        value: item.id,
    }))
  ), [products])

  const groupOptions = useMemo(() => (
    groups.map((item) => ({
        label: item.name,
        value: item.id,
    }))
  ), [groups])

  const categoryOptions = useMemo(() => (
    categories.map((item) => ({
        label: item.name,
        value: item.id,
    }))
  ), [categories])

  const scopeOptions = useMemo(() => {
    if (scope === "product") return productOptions
    if (scope === "group") return groupOptions
    if (scope === "category") return categoryOptions
    return []
  }, [categoryOptions, groupOptions, productOptions, scope])

  const openCreate = () => {
    setEditing(null)
    form.resetFields()
    form.setFieldsValue({
      code: "",
      type: "fixed",
      discount_level: "order",
      value: 0,
      scope: "all",
      scope_ids: [],
      max_uses: 0,
      max_uses_per_user: 0,
      applicable_cycles: [],
      min_order_amount: 0,
      min_quantity: 0,
      max_discount_amount: 0,
      required_product_ids: [],
      required_group_ids: [],
      required_category_ids: [],
      allowed_user_ids: [],
      new_users_only: false,
      applies_to_renewals: false,
      is_stackable: false,
      is_enabled: true,
    })
    setModalOpen(true)
  }

  const openEdit = (record: AdminPromoCode) => {
    setEditing(record)
    form.setFieldsValue({
      code: record.code,
      description: record.description,
      type: record.type,
      discount_level: record.discount_level,
      value: displayFormValue(record),
      scope: record.scope,
      scope_ids: record.scope_ids,
      starts_at: toLocalInput(record.starts_at),
      expires_at: toLocalInput(record.expires_at),
      max_uses: record.max_uses,
      max_uses_per_user: record.max_uses_per_user,
      applicable_cycles: record.applicable_cycles,
      min_order_amount: record.min_order_amount / 100,
      min_quantity: record.min_quantity,
      max_discount_amount: record.max_discount_amount / 100,
      required_product_ids: record.required_product_ids,
      required_group_ids: record.required_group_ids,
      required_category_ids: record.required_category_ids,
      allowed_user_ids: record.allowed_user_ids,
      new_users_only: record.new_users_only,
      applies_to_renewals: record.applies_to_renewals,
      is_stackable: record.is_stackable,
      is_enabled: record.is_enabled,
    })
    setModalOpen(true)
  }

  const toPayload = (values: PromoFormValues): AdminPromoCodePayload => ({
    code: values.code.trim().toUpperCase(),
    description: values.description?.trim() || null,
    type: values.type,
    value: backendValue(values.type, values.value),
    discount_level: values.discount_level,
    scope: values.scope,
    scope_ids: values.scope === "all" ? [] : (values.scope_ids ?? []),
    starts_at: toIso(values.starts_at),
    expires_at: toIso(values.expires_at),
    max_uses: values.max_uses ?? 0,
    max_uses_per_user: values.max_uses_per_user ?? 0,
    applicable_cycles: values.applicable_cycles ?? [],
    min_order_amount: Math.round((values.min_order_amount || 0) * 100),
    min_quantity: values.min_quantity ?? 0,
    max_discount_amount: Math.round((values.max_discount_amount || 0) * 100),
    required_product_ids: normalizeIds(values.required_product_ids),
    required_group_ids: normalizeIds(values.required_group_ids),
    required_category_ids: normalizeIds(values.required_category_ids),
    allowed_user_ids: normalizeIds(values.allowed_user_ids),
    new_users_only: values.new_users_only,
    applies_to_renewals: values.applies_to_renewals,
    is_stackable: values.is_stackable,
    is_enabled: values.is_enabled,
  })

  const handleSave = async () => {
    try {
      const values = await form.validateFields()
      setSaving(true)
      if (editing) {
        await updatePromoCode(editing.id, toPayload(values))
        message.success("优惠券已更新")
      } else {
        await createPromoCode(toPayload(values))
        message.success("优惠券已创建")
      }
      setModalOpen(false)
      await reload()
    } catch (e: unknown) {
      if (e && typeof e === "object" && "errorFields" in e) return
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "保存优惠券失败")
    } finally {
      setSaving(false)
    }
  }

  const handleToggle = async (record: AdminPromoCode) => {
    try {
      await updatePromoCode(record.id, { is_enabled: !record.is_enabled })
      message.success(record.is_enabled ? "已停用" : "已启用")
      await reload()
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "更新状态失败")
    }
  }

  const handleDelete = async (record: AdminPromoCode) => {
    try {
      await deletePromoCode(record.id)
      message.success("优惠券已删除")
      await reload()
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "删除优惠券失败")
    }
  }

  const columns: TableColumnsType<AdminPromoCode> = [
    {
      title: "优惠码",
      dataIndex: "code",
      width: 190,
      render: (value: string, record) => (
        <Space orientation="vertical" size={0}>
          <Text strong copyable>{value}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.description || "无说明"}</Text>
        </Space>
      ),
    },
    {
      title: "类型",
      width: 170,
      render: (_value, record) => {
        const level = levelMeta(record.discount_level)
        const type = typeMeta(record.type)
        return (
          <Space wrap>
            <Tag color={level.color}>{level.label}</Tag>
            <Tag color={type.color}>{type.label}</Tag>
          </Space>
        )
      },
    },
    {
      title: "优惠",
      dataIndex: "value",
      width: 130,
      render: (_value, record) => <Text strong>{formatValue(record)}</Text>,
    },
    {
      title: "适用范围",
      width: 170,
      render: (_value, record) => (
        <Space orientation="vertical" size={0}>
          <Text>{scopeLabel(record.scope)}</Text>
          {record.scope !== "all" && <Text type="secondary" style={{ fontSize: 12 }}>{(record.scope_ids ?? []).length} 个对象</Text>}
        </Space>
      ),
    },
    {
      title: "门槛",
      dataIndex: "min_order_amount",
      width: 120,
      render: (value: number) => value > 0 ? `满 ¥${centsToYuan(value)}` : "无门槛",
    },
    {
      title: "高级条件",
      width: 180,
      render: (_value, record) => {
        const conditionCount = [
          record.min_quantity > 0,
          record.max_discount_amount > 0,
          (record.required_product_ids ?? []).length > 0,
          (record.required_group_ids ?? []).length > 0,
          (record.required_category_ids ?? []).length > 0,
          (record.allowed_user_ids ?? []).length > 0,
        ].filter(Boolean).length
        return (
          <Space orientation="vertical" size={0}>
            <Text>{conditionCount > 0 ? `${conditionCount} 项条件` : "无额外条件"}</Text>
            {record.max_discount_amount > 0 && (
              <Text type="secondary" style={{ fontSize: 12 }}>封顶 ¥{centsToYuan(record.max_discount_amount)}</Text>
            )}
            {record.min_quantity > 0 && (
              <Text type="secondary" style={{ fontSize: 12 }}>满 {record.min_quantity} 件</Text>
            )}
          </Space>
        )
      },
    },
    {
      title: "使用",
      width: 150,
      render: (_value, record) => (
        <Space orientation="vertical" size={0}>
          <Text>{record.used_count} / {record.max_uses || "不限"}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>单用户 {record.max_uses_per_user || "不限"}</Text>
        </Space>
      ),
    },
    {
      title: "有效期",
      width: 210,
      render: (_value, record) => (
        <Space orientation="vertical" size={0}>
          <Text type="secondary" style={{ fontSize: 12 }}>起：{formatDate(record.starts_at)}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>止：{formatDate(record.expires_at)}</Text>
        </Space>
      ),
    },
    {
      title: "状态",
      dataIndex: "is_enabled",
      width: 100,
      render: (value: boolean, record) => (
        <Switch
          checked={value}
          checkedChildren="启用"
          unCheckedChildren="停用"
          onChange={() => void handleToggle(record)}
        />
      ),
    },
    {
      title: "操作",
      key: "actions",
      width: 110,
      align: "right",
      render: (_value, record) => (
        <Space size={4}>
          <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)} />
          <Button
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => {
              Modal.confirm({
                title: `删除优惠券 ${record.code}？`,
                content: record.used_count > 0 ? "该券已有使用次数，后端会阻止删除，请改为停用。" : "删除后不可恢复。",
                onOk: () => handleDelete(record),
              })
            }}
          />
        </Space>
      ),
    },
  ]

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row justify="space-between" align="bottom">
        <Col>
          <Title level={3}>优惠券管理</Title>
          <Paragraph type="secondary">
            创建订单级优惠券和产品级优惠券；产品级券在购物车使用时必须选择具体商品。
          </Paragraph>
        </Col>
        <Col>
          <Space>
            <Button icon={<ReloadOutlined />} loading={loading} onClick={() => void reload()}>刷新</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>新建优惠券</Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="优惠券总数" value={stats.total} prefix={<GiftOutlined />} /></Card></Col>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="已启用" value={stats.enabled} prefix={<CheckCircleOutlined />} styles={{ content: { color: "#52c41a" } }} /></Card></Col>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="已停用" value={stats.disabled} prefix={<CloseCircleOutlined />} styles={{ content: { color: "#ff4d4f" } }} /></Card></Col>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="产品级券" value={stats.productLevel} prefix={<TagOutlined />} /></Card></Col>
      </Row>

      <Card variant="outlined">
        <Row gutter={[12, 12]} justify="space-between">
          <Col xs={24} md={10}>
            <Input.Search
              allowClear
              placeholder="搜索优惠码或说明"
              onSearch={(value) => {
                setKeyword(value.trim())
                setPage(1)
              }}
            />
          </Col>
          <Col>
            <Space>
              <Select
                value={levelFilter}
                style={{ width: 130 }}
                options={[
                  { label: "全部层级", value: "all" },
                  { label: "订单级", value: "order" },
                  { label: "产品级", value: "product" },
                ]}
                onChange={(value) => {
                  setLevelFilter(value)
                  setPage(1)
                }}
              />
              <Select
                value={enabledFilter}
                style={{ width: 130 }}
                options={[
                  { label: "全部状态", value: "all" },
                  { label: "启用", value: true },
                  { label: "停用", value: false },
                ]}
                onChange={(value) => {
                  setEnabledFilter(value)
                  setPage(1)
                }}
              />
            </Space>
          </Col>
        </Row>
      </Card>

      <Card variant="outlined" title="优惠券列表">
        <Table<AdminPromoCode>
          rowKey={(record) => record.row_key || String(record.id || record.code)}
          loading={loading}
          columns={columns}
          dataSource={items}
          scroll={{ x: 1280 }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showTotal: (count) => `共 ${count} 张优惠券`,
          }}
          onChange={(next) => {
            setPage(next.current ?? 1)
            setPageSize(next.pageSize ?? 20)
          }}
          locale={{
            emptyText: (
              <Empty description="暂无优惠券">
                <Button type="primary" onClick={openCreate}>创建第一张优惠券</Button>
              </Empty>
            ),
          }}
        />
      </Card>

      <Modal
        title={editing ? "编辑优惠券" : "新建优惠券"}
        open={modalOpen}
        onOk={() => void handleSave()}
        onCancel={() => setModalOpen(false)}
        confirmLoading={saving}
        destroyOnHidden
        width={760}
      >
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item name="code" label="优惠码" rules={[{ required: true, message: "请输入优惠码" }]}>
                <Input
                  placeholder="例如 NEWUSER10"
                  addonAfter={
                    <Button
                      type="link"
                      size="small"
                      style={{ padding: 0 }}
                      onClick={() => form.setFieldValue("code", generateCouponCode())}
                    >
                      生成
                    </Button>
                  }
                />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="discount_level" label="优惠层级" rules={[{ required: true }]}>
                <Select
                  options={[
                    { label: "订单级：直接作用整单", value: "order" },
                    { label: "产品级：购物车必须选择商品", value: "product" },
                  ]}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="description" label="说明">
            <Input.TextArea rows={2} placeholder="运营备注或前台可展示说明" />
          </Form.Item>

          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item name="type" label="优惠类型" rules={[{ required: true }]}>
                <Select
                  options={[
                    { label: "百分比折扣", value: "percent" },
                    { label: "固定金额抵扣", value: "fixed" },
                    { label: "覆盖为固定价格", value: "override" },
                  ]}
                />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                name="value"
                label={couponType === "percent" ? "优惠百分比" : couponType === "override" ? "覆盖价格（元）" : "抵扣金额（元）"}
                rules={[{ required: true, message: "请输入优惠值" }]}
              >
                <InputNumber
                  min={0}
                  max={couponType === "percent" ? 100 : undefined}
                  precision={couponType === "percent" ? 0 : 2}
                  addonAfter={couponType === "percent" ? <PercentageOutlined /> : "元"}
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item name="scope" label="适用范围" rules={[{ required: true }]}>
                <Select
                  onChange={(value) => {
                    if (value === "all") form.setFieldValue("scope_ids", [])
                  }}
                  options={[
                    { label: "全场", value: "all" },
                    { label: "指定分类", value: "category" },
                    { label: "指定产品组", value: "group" },
                    { label: "指定产品", value: "product" },
                  ]}
                />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                name="scope_ids"
                label="适用对象"
                rules={scope && scope !== "all" ? [{ required: true, message: "请选择适用对象" }] : []}
              >
                <Select
                  mode="multiple"
                  allowClear
                  showSearch
                  disabled={!scope || scope === "all"}
                  optionFilterProp="label"
                  placeholder={scope === "all" ? "全场无需选择" : "请选择适用对象"}
                  options={scopeOptions}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} md={6}>
              <Form.Item name="min_order_amount" label="订单门槛（元）">
                <InputNumber min={0} precision={2} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col xs={24} md={6}>
              <Form.Item name="max_discount_amount" label="优惠封顶（元）">
                <InputNumber min={0} precision={2} addonAfter="0=不限" style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col xs={24} md={6}>
              <Form.Item name="max_uses" label="总使用次数">
                <InputNumber min={0} precision={0} addonAfter="0=不限" style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col xs={24} md={6}>
              <Form.Item name="max_uses_per_user" label="单用户次数">
                <InputNumber min={0} precision={0} addonAfter="0=不限" style={{ width: "100%" }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item name="starts_at" label="开始时间">
                <Input type="datetime-local" />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="expires_at" label="结束时间">
                <Input type="datetime-local" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="applicable_cycles" label="适用周期">
            <Select mode="multiple" allowClear placeholder="不选则任意周期" options={CYCLE_OPTIONS} />
          </Form.Item>

          <Card size="small" title="高级使用条件" style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col xs={24} md={8}>
                <Form.Item name="min_quantity" label="最低购买数量">
                  <InputNumber min={0} precision={0} addonAfter="0=不限" style={{ width: "100%" }} />
                </Form.Item>
              </Col>
              <Col xs={24} md={16}>
                <Form.Item name="allowed_user_ids" label="限定用户 ID">
                  <Select
                    mode="tags"
                    allowClear
                    tokenSeparators={[",", "，", " "]}
                    placeholder="不填则所有用户可用；可输入多个用户 ID"
                  />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item name="required_product_ids" label="订单必须包含产品">
              <Select
                mode="multiple"
                allowClear
                showSearch
                optionFilterProp="label"
                placeholder="不限制"
                options={productOptions}
              />
            </Form.Item>
            <Form.Item name="required_group_ids" label="订单必须包含产品组">
              <Select
                mode="multiple"
                allowClear
                showSearch
                optionFilterProp="label"
                placeholder="不限制"
                options={groupOptions}
              />
            </Form.Item>
            <Form.Item name="required_category_ids" label="订单必须包含分类">
              <Select
                mode="multiple"
                allowClear
                showSearch
                optionFilterProp="label"
                placeholder="不限制"
                options={categoryOptions}
              />
            </Form.Item>
          </Card>

          <Row gutter={16}>
            <Col xs={24} md={8}>
              <Form.Item name="new_users_only" label="仅新用户" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item name="applies_to_renewals" label="适用续费" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item name="is_enabled" label="启用" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="is_stackable" label="允许叠加其他优惠" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  )
}
