import { useEffect, useMemo, useState } from "react"
import {
  Alert,
  Button,
  Card,
  Col,
  Descriptions,
  Empty,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Space,
  Spin,
  Statistic,
  Switch,
  Table,
  Tabs,
  Tag,
  Typography,
  message,
} from "antd"
import type { ColumnsType } from "antd/es/table"
import {
  CopyOutlined,
  DollarOutlined,
  EditOutlined,
  GiftOutlined,
  LinkOutlined,
  PlusOutlined,
  ShareAltOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons"
import {
  applyAgent,
  getAgentCustomers,
  getAgentOverview,
  getAgentSettlements,
  listPublicAgentTiers,
  type AgentCustomerItem,
  type AgentOverview,
  type AgentSettlementItem,
  type AgentTier,
} from "../api/agent"
import {
  createPromotionCoupon,
  disablePromotionCoupon,
  getPromotionCoupons,
  getPromotionOverview,
  getPromotionRewards,
  updatePromotionInviteCode,
  type CreatePromotionCouponPayload,
  type PromotionCoupon,
  type PromotionOverview,
  type PromotionReward,
} from "../api/promotion"
import { formatPoints, formatYuan } from "../utils/format"

const { Text, Title } = Typography

interface CouponFormValues {
  code?: string
  description?: string
  type: "fixed" | "threshold_fixed" | "percent"
  value: number | null
  threshold_amount: number | null
  max_discount_amount: number | null
  max_uses: number
  max_uses_per_user: number
  expires_at?: string
  claim_method: "code" | "mall"
  list_on_mall: boolean
  points_price: number | null
  stock_total: number | null
  mall_title: string | null
  mall_subtitle: string | null
  mall_cover_image: string | null
  mall_category: string | null
  mall_scope: "public" | "agent_subordinates"
  mall_sort_order: number | null
}

interface ApplyFormValues {
  tier: string
  reason: string
  channels: string
}

function errorDetail(error: unknown, fallback: string) {
  const detail = (error as { response?: { data?: { detail?: unknown } } })?.response?.data?.detail
  if (typeof detail === "string" && detail.trim()) return detail
  if (detail && typeof detail === "object") {
    const data = detail as { message?: unknown; reason?: unknown; error?: unknown }
    const message = data.message ?? data.reason ?? data.error
    if (typeof message === "string" && message.trim()) return message
  }
  return fallback
}

function formatDate(value: string | null | undefined) {
  return value ? new Date(value).toLocaleString() : "-"
}

function formatRate(rate: number | null | undefined) {
  return `${((rate ?? 0) / 100).toFixed(1)}%`
}

function couponAmount(coupon: PromotionCoupon) {
  if (coupon.type === "fixed") return `立减 ${formatYuan(coupon.value)}`
  if (coupon.type === "threshold_fixed") return `满 ${formatYuan(coupon.threshold_amount)} 减 ${formatYuan(coupon.value)}`
  if (coupon.type === "percent") return `${coupon.value / 10} 折`
  return `覆盖到 ${formatYuan(coupon.value)}`
}

function couponStatus(coupon: PromotionCoupon) {
  if (!coupon.is_enabled) return <Tag>已停用</Tag>
  if (coupon.expires_at && new Date(coupon.expires_at).getTime() < Date.now()) return <Tag color="red">已过期</Tag>
  if (coupon.max_uses > 0 && coupon.used_count >= coupon.max_uses) return <Tag color="gold">已用完</Tag>
  return <Tag color="green">启用中</Tag>
}

function issuerTag(value: string | null) {
  if (value === "agent") return <Tag color="blue">代理券</Tag>
  if (value === "member") return <Tag color="green">会员券</Tag>
  return <Tag>平台券</Tag>
}

function settlementTypeLabel(type: string) {
  if (type === "agent_profit") return "代理收益"
  if (type === "agent_subsidy") return "代理补贴"
  if (type === "member_commission") return "推广奖励"
  return type
}

export default function Promotion() {
  const [loading, setLoading] = useState(true)
  const [overview, setOverview] = useState<PromotionOverview | null>(null)
  const [rewards, setRewards] = useState<PromotionReward[]>([])
  const [coupons, setCoupons] = useState<PromotionCoupon[]>([])
  const [couponTotal, setCouponTotal] = useState(0)
  const [agentOverview, setAgentOverview] = useState<AgentOverview | null>(null)
  const [agentTiers, setAgentTiers] = useState<AgentTier[]>([])
  const [customers, setCustomers] = useState<AgentCustomerItem[]>([])
  const [settlements, setSettlements] = useState<AgentSettlementItem[]>([])
  const [codeModalOpen, setCodeModalOpen] = useState(false)
  const [couponModalOpen, setCouponModalOpen] = useState(false)
  const [savingCode, setSavingCode] = useState(false)
  const [savingCoupon, setSavingCoupon] = useState(false)
  const [applyingAgent, setApplyingAgent] = useState(false)
  const [codeForm] = Form.useForm<{ invite_code: string }>()
  const [couponForm] = Form.useForm<CouponFormValues>()
  const [applyForm] = Form.useForm<ApplyFormValues>()



  const activeAgent = agentOverview?.agent?.status === "active"
  const availablePoints = overview?.available_points ?? agentOverview?.available_points ?? 0
  const memberLevel = Number(overview?.member_level ?? 0)
  const minAgentLevel = agentTiers.length > 0 ? Math.min(...agentTiers.map((tier) => tier.min_member_level)) : 0
  const eligibleAgentTiers = agentTiers.filter((tier) => memberLevel >= tier.min_member_level)
  const couponType = Form.useWatch("type", couponForm) ?? "fixed"
  const couponClaimMethod = Form.useWatch("claim_method", couponForm) ?? "code"
  const couponListOnMall = Boolean(Form.useWatch("list_on_mall", couponForm))
  const couponValue = Number(Form.useWatch("value", couponForm) || 0)
  const couponMaxUses = Number(Form.useWatch("max_uses", couponForm) || 0)
  const couponMaxDiscount = Number(Form.useWatch("max_discount_amount", couponForm) || 0)
  const isPercent = couponType === "percent"
  // 会员券预扣积分 = 单张最大优惠金额（分） × 总次数 × 1000 / 100
  const maxDiscountPerUse = isPercent ? couponMaxDiscount : couponValue
  const couponPointCost = !activeAgent ? Math.max(0, maxDiscountPerUse) * couponMaxUses * 10 : 0

  async function loadAgentLists(isActive: boolean) {
    if (!isActive) {
      setCustomers([])
      setSettlements([])
      return
    }
    try {
      const [customerRes, settlementRes] = await Promise.all([
        getAgentCustomers(0, 20),
        getAgentSettlements(0, 20),
      ])
      setCustomers(customerRes.data?.items ?? [])
      setSettlements(settlementRes.data?.items ?? [])
    } catch {
      setCustomers([])
      setSettlements([])
    }
  }

  async function loadData() {
    setLoading(true)
    try {
      const [ov, rewardLogs, couponRes, agentRes, tierRes] = await Promise.all([
        getPromotionOverview(),
        getPromotionRewards(20, 0),
        getPromotionCoupons(50, 0),
        getAgentOverview(),
        listPublicAgentTiers(),
      ])
      setOverview(ov)
      setRewards(rewardLogs)
      setCoupons(couponRes.items)
      setCouponTotal(couponRes.total)
      const agentData = agentRes.data ?? null
      setAgentOverview(agentData)
      setAgentTiers(tierRes.data ?? [])
      await loadAgentLists(agentData?.agent?.status === "active")
    } catch (error) {
      message.error(errorDetail(error, "加载推广中心失败"))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const copy = (text: string) => {
    navigator.clipboard.writeText(text).then(() => message.success("已复制")).catch(() => message.error("复制失败"))
  }

  const openCodeModal = () => {
    if (!overview?.invite_code_edit_enabled) {
      message.warning("当前暂不支持修改推广码")
      return
    }
    if ((overview.invite_code_change_remaining ?? 0) <= 0) {
      message.warning("邀请码修改次数已用完")
      return
    }
    const currentCode = overview?.invite_code ?? ""
    codeForm.setFieldsValue({
      invite_code: /^[A-Za-z0-9]{3,8}$/.test(currentCode) ? currentCode : "",
    })
    setCodeModalOpen(true)
  }

  const saveInviteCode = async () => {
    try {
      const values = await codeForm.validateFields()
      setSavingCode(true)
      const updated = await updatePromotionInviteCode(values.invite_code)
      setOverview((prev) => prev ? { ...prev, ...updated } : prev)
      setCodeModalOpen(false)
      message.success("推广码已更新")
    } catch (error: unknown) {
      if (error && typeof error === "object" && "errorFields" in error) return
      message.error(errorDetail(error, "推广码更新失败"))
    } finally {
      setSavingCode(false)
    }
  }

  const openCouponModal = () => {
    couponForm.setFieldsValue({
      type: "fixed",
      value: 100,
      threshold_amount: null,
      max_discount_amount: null,
      max_uses: 1,
      max_uses_per_user: 1,
      claim_method: "code",
      list_on_mall: false,
      points_price: null,
      stock_total: null,
      mall_title: null,
      mall_subtitle: null,
      mall_cover_image: null,
      mall_category: null,
      mall_scope: "public",
      mall_sort_order: 0,
    })
    setCouponModalOpen(true)
  }

  const createCoupon = async () => {
    try {
      const values = await couponForm.validateFields()
      if (!activeAgent && couponPointCost > availablePoints) {
        message.error(`积分不足：需要 ${formatPoints(couponPointCost)} 积分，当前可用 ${formatPoints(availablePoints)} 积分`)
        return
      }
      if ((values.claim_method === "mall" || values.list_on_mall) && (!values.points_price || !values.stock_total)) {
        message.error("上架积分商城时，请填写领取所需积分和库存数量")
        return
      }
      const payload: CreatePromotionCouponPayload = {
        code: values.code?.trim() || undefined,
        description: values.description?.trim() || undefined,
        type: values.type,
        value: values.type === "percent" ? Math.round(values.value || 0) : Math.round((values.value || 0) * 100),
        threshold_amount: values.threshold_amount ? Math.round(values.threshold_amount * 100) : null,
        max_discount_amount: values.max_discount_amount ? Math.round(values.max_discount_amount * 100) : null,
        max_uses: Number(values.max_uses),
        max_uses_per_user: Number(values.max_uses_per_user),
        expires_at: values.expires_at ? new Date(values.expires_at).toISOString() : null,
        claim_method: values.claim_method,
        list_on_mall: values.list_on_mall,
        points_price: values.points_price ? Number(values.points_price) : null,
        stock_total: values.stock_total ? Number(values.stock_total) : null,
        mall_title: values.mall_title?.trim() || null,
        mall_subtitle: values.mall_subtitle?.trim() || null,
        mall_cover_image: values.mall_cover_image?.trim() || null,
        mall_category: values.mall_category?.trim() || null,
        mall_scope: values.mall_scope,
        mall_sort_order: values.mall_sort_order ? Number(values.mall_sort_order) : 0,
      }
      setSavingCoupon(true)
      const data = await createPromotionCoupon(payload)
      setCoupons((prev) => [data.coupon, ...prev])
      setCouponTotal((prev) => prev + 1)
      if (data.available_points !== undefined) {
        const points = data.available_points ?? 0
        setOverview((prev) => prev ? { ...prev, available_points: points } : prev)
        setAgentOverview((prev) => prev ? { ...prev, available_points: points } : prev)
      }
      setCouponModalOpen(false)
      message.success("优惠券已创建")
    } catch (error: unknown) {
      if (error && typeof error === "object" && "errorFields" in error) return
      message.error(errorDetail(error, "创建优惠券失败"))
    } finally {
      setSavingCoupon(false)
    }
  }


  const confirmDisableCoupon = (coupon: PromotionCoupon) => {
    Modal.confirm({
      title: coupon.issuer_type === "member" ? "停用并返还未使用积分" : "停用优惠券",
      content: coupon.issuer_type === "member"
        ? `将停用 ${coupon.code}，预计返还 ${formatPoints(coupon.refundable_points)} 积分。`
        : `将停用 ${coupon.code}。`,
      okText: "确认停用",
      okButtonProps: { danger: true },
      cancelText: "取消",
      onOk: async () => {
        const data = await disablePromotionCoupon(coupon.id)
        setCoupons((prev) => prev.map((item) => item.id === coupon.id ? data.coupon : item))
        if (data.available_points !== undefined) {
          const points = data.available_points ?? 0
          setOverview((prev) => prev ? { ...prev, available_points: points } : prev)
          setAgentOverview((prev) => prev ? { ...prev, available_points: points } : prev)
        }
        message.success(data.refunded_points > 0 ? `已返还 ${formatPoints(data.refunded_points)} 积分` : "优惠券已停用")
      },
    })
  }

  const submitAgentApply = async () => {
    try {
      const values = await applyForm.validateFields()
      const tier = agentTiers.find((item) => item.code === values.tier)
      if (!tier) {
        message.error("请选择有效的代理档位")
        return
      }
      if (memberLevel < tier.min_member_level) {
        message.error(`当前会员等级 LV${memberLevel}，该档位需要 LV${tier.min_member_level}+`)
        return
      }
      setApplyingAgent(true)
      await applyAgent(values.tier, values.reason, values.channels)
      message.success("代理申请已提交")
      await loadData()
    } catch (error: unknown) {
      if (error && typeof error === "object" && "errorFields" in error) return
      message.error(errorDetail(error, "代理申请提交失败"))
    } finally {
      setApplyingAgent(false)
    }
  }

  const couponColumns = useMemo<ColumnsType<PromotionCoupon>>(() => [
    {
      title: "优惠券",
      dataIndex: "code",
      render: (_value, record) => (
        <Space orientation="vertical" size={0}>
          <Text strong copyable>{record.code}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.description || "-"}</Text>
        </Space>
      ),
    },
    {
      title: "来源",
      dataIndex: "issuer_type",
      width: 100,
      render: issuerTag,
    },
    {
      title: "优惠",
      width: 110,
      render: (_, record) => <Text strong>{couponAmount(record)}</Text>,
    },
    {
      title: "使用",
      width: 120,
      render: (_, record) => `${record.used_count}/${record.max_uses || "不限"}`,
    },
    {
      title: "积分",
      width: 190,
      render: (_, record) => record.issuer_type === "member" ? (
        <Space orientation="vertical" size={0}>
          <Text>{formatPoints(record.point_cost)} 扣除</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>
            已返 {formatPoints(record.point_refunded)} / 可返 {formatPoints(record.refundable_points)}
          </Text>
        </Space>
      ) : <Text type="secondary">使用时按代理结算</Text>,
    },
    {
      title: "有效期",
      dataIndex: "expires_at",
      width: 180,
      render: formatDate,
    },
    {
      title: "状态",
      width: 100,
      render: (_, record) => couponStatus(record),
    },
    {
      title: "操作",
      width: 120,
      render: (_, record) => (
        <Button
          type="link"
          danger
          disabled={!record.is_enabled}
          onClick={() => confirmDisableCoupon(record)}
        >
          停用
        </Button>
      ),
    },
  ], [])

  const rewardColumns = useMemo<ColumnsType<PromotionReward>>(() => [
    { title: "时间", dataIndex: "created_at", width: 180, render: formatDate },
    { title: "关联单号", dataIndex: "ref_no", render: (value: string | null) => value || "-" },
    {
      title: "状态",
      dataIndex: "status",
      width: 130,
      render: (value: string, row) => {
        const color = value === "settled" ? "green" : value === "frozen" ? "gold" : value === "reversed" ? "red" : "default"
        return <Tag color={color}>{row.status_label || value}</Tag>
      },
    },
    { title: "备注", dataIndex: "remark", render: (value: string | null) => value || "-" },
    {
      title: "积分",
      dataIndex: "points",
      align: "right",
      width: 140,
      render: (value: number, row) => (
        <Text type={row.status === "reversed" ? "danger" : "success"} strong>
          {row.status === "reversed" ? "-" : "+"}{formatPoints(value)}
        </Text>
      ),
    },
  ], [])

  const customerColumns = useMemo<ColumnsType<AgentCustomerItem>>(() => [
    {
      title: "客户",
      render: (_, record) => (
        <Space orientation="vertical" size={0}>
          <Text strong>{record.customer?.nickname || record.customer?.username || `#${record.customer_user_id}`}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.customer?.email || record.customer?.phone || "-"}</Text>
        </Space>
      ),
    },
    { title: "绑定来源", dataIndex: "bind_source", width: 120 },
    { title: "绑定时间", dataIndex: "bound_at", width: 180, render: formatDate },
    { title: "状态", dataIndex: "status", width: 100, render: (value: string) => <Tag>{value}</Tag> },
  ], [])

  const settlementColumns = useMemo<ColumnsType<AgentSettlementItem>>(() => [
    { title: "时间", dataIndex: "created_at", width: 180, render: formatDate },
    { title: "单号", dataIndex: "order_no", render: (value: string) => value || "-" },
    { title: "类型", dataIndex: "settlement_type", width: 120, render: settlementTypeLabel },
    { title: "实付", dataIndex: "customer_pay_amount", align: "right", width: 120, render: formatYuan },
    { title: "差额", dataIndex: "delta_amount", align: "right", width: 120, render: (value: number) => <Text type={value < 0 ? "danger" : "success"}>{formatYuan(value)}</Text> },
    { title: "积分", dataIndex: "points_amount", align: "right", width: 120, render: (value: number) => formatPoints(value || 0) },
    { title: "状态", dataIndex: "status", width: 110, render: (value: string) => <Tag>{value}</Tag> },
  ], [])

  if (loading) {
    return <Spin size="large" description="加载推广中心" style={{ display: "flex", justifyContent: "center", padding: 80 }} />
  }

  const linkTab = (
    <Space orientation="vertical" size={16} style={{ width: "100%" }}>
      <Row gutter={[16, 16]}>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="当前奖励比例" value={formatRate(overview?.reward_rate)} prefix={<GiftOutlined />} /></Card></Col>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="推广点击" value={overview?.click_count ?? 0} prefix={<ShareAltOutlined />} /></Card></Col>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="绑定用户" value={overview?.registered_count ?? 0} prefix={<TeamOutlined />} /></Card></Col>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="可用积分" value={formatPoints(availablePoints)} prefix={<GiftOutlined />} /></Card></Col>
      </Row>

      <Card variant="outlined" title={<Space><LinkOutlined />推广链接</Space>}>
        <Descriptions column={1} size="middle">
          <Descriptions.Item label="会员等级">LV{overview?.member_level ?? "-"} {overview?.member_level_name ?? ""}</Descriptions.Item>
          <Descriptions.Item label="推广码">
            <Space>
              <Text strong copyable>{overview?.invite_code}</Text>
              <Button size="small" icon={<CopyOutlined />} onClick={() => copy(overview?.invite_code ?? "")} />
              <Button
                size="small"
                icon={<EditOutlined />}
                disabled={!overview?.invite_code_edit_enabled || (overview?.invite_code_change_remaining ?? 0) <= 0}
                onClick={openCodeModal}
              >
                修改
              </Button>
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="修改次数">
            已用 {overview?.invite_code_change_count ?? 0} / {overview?.invite_code_change_limit ?? 3}，剩余 {overview?.invite_code_change_remaining ?? 0} 次
          </Descriptions.Item>
          <Descriptions.Item label="注册链接">
            <Space wrap>
              <Text code style={{ fontSize: 12 }}>{overview?.invite_link}</Text>
              <Button size="small" icon={<CopyOutlined />} onClick={() => copy(overview?.invite_link ?? "")}>复制</Button>
            </Space>
          </Descriptions.Item>
        </Descriptions>
      </Card>
    </Space>
  )

  const couponTab = (
    <Space orientation="vertical" size={16} style={{ width: "100%" }}>
      <Row gutter={[16, 16]}>
        <Col xs={24} md={8}><Card variant="outlined"><Statistic title="已创建优惠券" value={couponTotal} prefix={<GiftOutlined />} /></Card></Col>
        <Col xs={24} md={8}><Card variant="outlined"><Statistic title={activeAgent ? "代理可用余额" : "可用积分"} value={activeAgent ? formatYuan(agentOverview?.agent?.agent_balance ?? 0) : formatPoints(availablePoints)} prefix={<GiftOutlined />} /></Card></Col>
        <Col xs={24} md={8}><Card variant="outlined"><Statistic title="代理状态" value={activeAgent ? "已激活" : "未激活"} prefix={<UserOutlined />} /></Card></Col>
      </Row>

      <Card
        variant="outlined"
        title="发券管理"
        extra={<Button type="primary" icon={<PlusOutlined />} onClick={openCouponModal}>创建优惠券</Button>}
      >
        {coupons.length === 0 ? (
          <Empty description="暂无优惠券" />
        ) : (
          <Table<PromotionCoupon>
            rowKey="id"
            size="small"
            columns={couponColumns}
            dataSource={coupons}
            pagination={{ pageSize: 10 }}
          />
        )}
      </Card>
    </Space>
  )

  const agentTab = (
    <Space orientation="vertical" size={16} style={{ width: "100%" }}>
      {agentOverview?.agent ? (
        <Card variant="outlined" title="代理身份">
          <Descriptions column={{ xs: 1, md: 2 }} size="middle">
            <Descriptions.Item label="状态"><Tag color={activeAgent ? "green" : "gold"}>{agentOverview.agent.status}</Tag></Descriptions.Item>
            <Descriptions.Item label="档位">{agentOverview.agent.agent_tier?.name || "-"}</Descriptions.Item>
            <Descriptions.Item label="成本折扣">{formatRate(agentOverview.agent.agent_tier?.cost_rate)}</Descriptions.Item>
            <Descriptions.Item label="代理余额">{formatYuan(agentOverview.agent.agent_balance)}</Descriptions.Item>
            <Descriptions.Item label="冻结余额">{formatYuan(agentOverview.agent.agent_frozen_balance)}</Descriptions.Item>
            <Descriptions.Item label="每月发券上限">{agentOverview.agent.agent_tier?.max_monthly_coupon_count ?? "-"}</Descriptions.Item>
            <Descriptions.Item label="累计销售">{formatYuan(agentOverview.total_sales)}</Descriptions.Item>
            <Descriptions.Item label="累计收益">{formatYuan(agentOverview.total_profit)}</Descriptions.Item>
          </Descriptions>
          {agentOverview.agent.review_message ? <Alert style={{ marginTop: 16 }} type="info" showIcon title={agentOverview.agent.review_message} /> : null}
        </Card>
      ) : null}

      {!activeAgent ? (
        <Card variant="outlined" title="申请代理">
          {minAgentLevel > 0 && memberLevel < minAgentLevel ? (
            <Alert
              type="warning"
              showIcon
              style={{ marginBottom: 16 }}
              title={`当前会员等级 LV${memberLevel}，申请代理最低需要 LV${minAgentLevel}+`}
            />
          ) : null}
          <Form form={applyForm} layout="vertical" style={{ maxWidth: 720 }}>
            <Form.Item name="tier" label="申请档位" rules={[{ required: true, message: "请选择代理档位" }]}>
              <Select
                placeholder={eligibleAgentTiers.length ? "选择代理档位" : "当前会员等级暂不可申请代理"}
                options={agentTiers.map((tier) => ({
                  value: tier.code,
                  label: `${tier.name} / 成本 ${formatRate(tier.cost_rate)} / LV${tier.min_member_level}+`,
                  disabled: memberLevel < tier.min_member_level,
                }))}
              />
            </Form.Item>
            <Form.Item name="channels" label="推广渠道" rules={[{ required: true, message: "请填写推广渠道" }]}>
              <Input.TextArea rows={3} maxLength={300} />
            </Form.Item>
            <Form.Item name="reason" label="申请说明" rules={[{ required: true, message: "请填写申请说明" }]}>
              <Input.TextArea rows={4} maxLength={500} />
            </Form.Item>
            <Button type="primary" loading={applyingAgent} disabled={eligibleAgentTiers.length === 0} onClick={submitAgentApply}>提交申请</Button>
          </Form>
        </Card>
      ) : null}
    </Space>
  )

  const memberTab = (
    <Space orientation="vertical" size={16} style={{ width: "100%" }}>
      <Row gutter={[16, 16]}>
        <Col xs={24} md={8}><Card variant="outlined"><Statistic title="会员等级" value={`LV${overview?.member_level ?? "-"}`} prefix={<UserOutlined />} /></Card></Col>
        <Col xs={24} md={8}><Card variant="outlined"><Statistic title="可用积分" value={formatPoints(availablePoints)} prefix={<GiftOutlined />} /></Card></Col>
        <Col xs={24} md={8}><Card variant="outlined"><Statistic title="推广奖励比例" value={formatRate(overview?.reward_rate)} prefix={<DollarOutlined />} /></Card></Col>
      </Row>
      <Card variant="outlined" title="会员发券规则">
        <Descriptions column={1} size="middle">
          <Descriptions.Item label="优惠类型">固定金额、满减</Descriptions.Item>
          <Descriptions.Item label="创建扣除">单张最大优惠 × 总次数 × 1000 积分</Descriptions.Item>
          <Descriptions.Item label="停用返还">未使用次数对应积分自动返还</Descriptions.Item>
        </Descriptions>
      </Card>
    </Space>
  )

  const customersTab = (
    <Space orientation="vertical" size={16} style={{ width: "100%" }}>
      {!activeAgent ? <Alert type="info" showIcon title="代理身份激活后可查看客户和收益。" /> : null}
      <Card variant="outlined" title="代理客户">
        {customers.length === 0 ? <Empty description="暂无代理客户" /> : <Table<AgentCustomerItem> rowKey="id" size="small" columns={customerColumns} dataSource={customers} pagination={false} />}
      </Card>
      <Card variant="outlined" title="收益流水">
        {settlements.length === 0 ? <Empty description="暂无收益流水" /> : <Table<AgentSettlementItem> rowKey="id" size="small" columns={settlementColumns} dataSource={settlements} pagination={false} />}
      </Card>
    </Space>
  )

  const rewardsTab = (
    <Card variant="outlined" title="推广奖励流水">
      {rewards.length === 0 ? <Empty description="暂无推广奖励" /> : <Table<PromotionReward> rowKey="id" size="small" columns={rewardColumns} dataSource={rewards} pagination={false} />}
    </Card>
  )

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <div>
        <Title level={3} style={{ marginBottom: 4 }}>推广中心</Title>
        <Text type="secondary">推广链接、会员发券、代理身份和收益统一在这里管理。</Text>
      </div>

      <Tabs
        items={[
          { key: "link", label: "推广链接", children: linkTab },
          { key: "coupons", label: "发券", children: couponTab },
          { key: "agent", label: "代理", children: agentTab },
          { key: "member", label: "会员", children: memberTab },
          { key: "customers", label: "客户收益", children: customersTab },
          { key: "rewards", label: "奖励流水", children: rewardsTab },
        ]}
      />

      <Modal
        title="修改推广码"
        open={codeModalOpen}
        onOk={saveInviteCode}
        onCancel={() => setCodeModalOpen(false)}
        confirmLoading={savingCode}
        destroyOnHidden
        okText="保存"
        cancelText="取消"
      >
        <Form form={codeForm} layout="vertical" style={{ marginTop: 16 }}>
          <Alert
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
            title={`旧邀请码会继续有效；每个账号最多可修改 ${overview?.invite_code_change_limit ?? 3} 次，当前剩余 ${overview?.invite_code_change_remaining ?? 0} 次。`}
          />
          <Form.Item
            name="invite_code"
            label="推广码"
            rules={[
              { required: true, message: "请输入推广码" },
              { min: 3, max: 8, message: "推广码需要 3~8 位" },
              { pattern: /^[A-Za-z0-9]+$/, message: "仅支持字母和数字" },
            ]}
            normalize={(value: string) => value?.trim().toUpperCase()}
          >
            <Input maxLength={8} placeholder="例如 QY888" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={activeAgent ? "创建代理优惠券" : "创建会员优惠券"}
        open={couponModalOpen}
        onOk={createCoupon}
        onCancel={() => setCouponModalOpen(false)}
        confirmLoading={savingCoupon}
        okButtonProps={{ disabled: !activeAgent && couponPointCost > availablePoints }}
        destroyOnHidden
        width={680}
        okText="创建"
        cancelText="取消"
      >
        <Form form={couponForm} layout="vertical" style={{ marginTop: 16 }}>
          <Alert
            style={{ marginBottom: 16 }}
            type="info"
            showIcon
            title={activeAgent ? "当前为代理身份，可创建固定、满减、折扣券" : "当前为会员身份，仅可创建固定金额券或满减券"}
          />
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item name="type" label="优惠类型" rules={[{ required: true }]}>
                <Select
                  options={activeAgent
                    ? [
                        { value: "fixed", label: "立减（固定金额）" },
                        { value: "threshold_fixed", label: "满减" },
                        { value: "percent", label: "折扣（百分比）" },
                      ]
                    : [
                        { value: "fixed", label: "立减（固定金额）" },
                        { value: "threshold_fixed", label: "满减" },
                      ]}
                />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                name="value"
                label={couponType === "percent" ? "折扣（%）" : "优惠金额（元）"}
                rules={[{ required: true, message: couponType === "percent" ? "请输入折扣" : "请输入优惠金额" }]}
              >
                <InputNumber
                  min={couponType === "percent" ? 1 : 0.01}
                  max={couponType === "percent" ? 100 : undefined}
                  precision={couponType === "percent" ? 0 : 2}
                  style={{ width: "100%" }}
                  placeholder={couponType === "percent" ? "例如 30 表示 3 折" : "例如 10 元"}
                />
              </Form.Item>
            </Col>
          </Row>
          {couponType === "threshold_fixed" && (
            <Form.Item name="threshold_amount" label="满减门槛（元）" rules={[{ required: true, message: "请输入满减门槛" }]}>
              <InputNumber min={0.01} precision={2} style={{ width: "100%" }} placeholder="例如 100 元" />
            </Form.Item>
          )}
          {couponType === "percent" && (
            <Form.Item name="max_discount_amount" label="最高优惠金额（元）" tooltip="折扣优惠封顶金额，0 表示不封顶">
              <InputNumber min={0} precision={2} style={{ width: "100%" }} placeholder="可选" />
            </Form.Item>
          )}
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item name="max_uses" label="总次数" rules={[{ required: true, message: "请输入总次数" }]}>
                <InputNumber min={1} max={1000} precision={0} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="max_uses_per_user" label="每人可用次数" rules={[{ required: true, message: "请输入每人可用次数" }]}>
                <InputNumber min={1} max={100} precision={0} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item name="claim_method" label="领取方式" rules={[{ required: true }]}>
                <Select
                  options={[
                    { value: "code", label: "优惠码" },
                    { value: "mall", label: "商城领取" },
                  ]}
                />
              </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="list_on_mall" valuePropName="checked" label={null}>
            <Switch checkedChildren="上架商城" unCheckedChildren="不上架商城" />
          </Form.Item>
          {(couponClaimMethod === "mall" || couponListOnMall) && (
            <>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Form.Item name="points_price" label="领取所需积分" rules={[{ required: true, message: "请输入领取积分" }]}>
                    <InputNumber min={1} precision={0} style={{ width: "100%" }} />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item name="stock_total" label="库存数量" rules={[{ required: true, message: "请输入库存" }]}>
                    <InputNumber min={1} precision={0} style={{ width: "100%" }} />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Form.Item name="mall_title" label="商城标题">
                    <Input maxLength={200} placeholder="留空使用券说明" />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item name="mall_category" label="商城分类">
                    <Input maxLength={50} placeholder="例如：新人专享" />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item name="mall_subtitle" label="商城副标题">
                <Input maxLength={500} placeholder="简短描述吸引用户" />
              </Form.Item>
              <Form.Item name="mall_cover_image" label="封面图 URL">
                <Input maxLength={500} placeholder="https://..." />
              </Form.Item>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Form.Item name="mall_scope" label="可见范围" rules={[{ required: true }]}>
                    <Select
                      options={[
                        { value: "public", label: "全站公开" },
                        { value: "agent_subordinates", label: "仅我绑定的客户/下级可见" },
                      ]}
                    />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item name="mall_sort_order" label="排序权重">
                    <InputNumber min={0} precision={0} style={{ width: "100%" }} />
                  </Form.Item>
                </Col>
              </Row>
            </>
          )}
          <Form.Item name="code" label="优惠码">
            <Input maxLength={16} placeholder="留空自动生成" />
          </Form.Item>
          <Form.Item name="description" label="说明">
            <Input.TextArea rows={3} maxLength={255} />
          </Form.Item>
          {!activeAgent && (
            <Alert
              type={couponPointCost > availablePoints ? "warning" : "info"}
              showIcon
              title={`预计扣除 ${formatPoints(couponPointCost)} 积分，当前可用 ${formatPoints(availablePoints)} 积分`}
            />
          )}
        </Form>
      </Modal>
    </Space>
  )
}
