import { useCallback, useEffect, useRef, useState } from "react"
import {
  Alert,
  Button,
  Card,
  Col,
  Empty,
  Input,
  Modal,
  QRCode,
  Row,
  Space,
  Statistic,
  Table,
  Tabs,
  Tag,
  Typography,
  type TableColumnsType,
} from "antd"
import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  CreditCardOutlined,
  ExclamationCircleOutlined,
  HistoryOutlined,
  ReloadOutlined,
  RollbackOutlined,
  WalletOutlined,
} from "@ant-design/icons"
import { getMe } from "../api/auth"
import {
  createRecharge,
  getPendingRecharge,
  listRechargePaymentOptions,
  listRechargeOrders,
  pollRechargeStatus,
  type PendingRechargePayment,
  type RechargeOrder,
  type RechargePaymentOption,
} from "../api/recharge"
import {
  listServiceOrders,
  unsubscribeOrder,
  type ServiceOrder,
  type ServiceOrderRefundPolicy,
} from "../api/orders"
import type { UpstreamActionLog } from "../api/upstreamActions"
import { useAuth } from "../contexts/AuthContext"
import type { User } from "../types"
import { toast } from "../utils/toast"

const { Title, Text, Paragraph } = Typography

const RECHARGE_STATUS_META = {
  pending: { label: "待支付", color: "warning", icon: <ClockCircleOutlined /> },
  paid: { label: "已到账", color: "success", icon: <CheckCircleOutlined /> },
  expired: { label: "已过期", color: "default", icon: <CloseCircleOutlined /> },
  closed: { label: "已关闭", color: "default", icon: <CloseCircleOutlined /> },
  refunded: { label: "已退款", color: "purple", icon: <ExclamationCircleOutlined /> },
} as const

const ORDER_STATUS_META: Record<string, { label: string; color: string }> = {
  pending: { label: "待处理", color: "warning" },
  paid: { label: "已支付", color: "green" },
  cancelled: { label: "已退订", color: "default" },
  refunded: { label: "已退款", color: "purple" },
}

const REFUND_TYPE_META: Record<string, { label: string; color: string }> = {
  full: { label: "全额退订", color: "green" },
  prorated: { label: "实额退订", color: "blue" },
  no_refund: { label: "不退款退订", color: "red" },
  unavailable: { label: "不可退订", color: "default" },
}

const RESOURCE_STATUS_META: Record<string, { label: string; color: string }> = {
  none: { label: "无资源动作", color: "default" },
  running: { label: "资源处理中", color: "processing" },
  failed: { label: "资源异常", color: "red" },
  finished: { label: "资源已处理", color: "green" },
  manual_handled: { label: "人工已处理", color: "purple" },
  ignored: { label: "无需处理", color: "default" },
}

const ACTION_TYPE_LABEL: Record<string, string> = {
  instance_delete: "强制删除实例",
  instance_suspend: "暂停实例",
  instance_unsuspend: "解除暂停",
  disk_delete: "删除云盘",
  disk_resize_rollback: "回退云盘容量",
  package_instance_rollback: "回退套餐配置",
  package_bandwidth_rollback: "回退带宽配置",
}

const CHANNEL_LABEL: Record<string, string> = {
  alipay: "支付宝",
  wxpay: "微信支付",
  qqpay: "QQ钱包",
  admin: "管理员调账",
}

const PRESET_AMOUNTS = [10, 30, 50, 100, 200, 500]
const BOOTSTRAP_CACHE_MS = 5000

interface FinancePrimaryData {
  rechargeOrders: RechargeOrder[]
  serviceOrders: ServiceOrder[]
  me: User | null
  ok: boolean
  failedSections: string[]
}

let primaryCache: { at: number; data: FinancePrimaryData } | null = null
let primaryPromise: Promise<FinancePrimaryData> | null = null
let pendingPromise: Promise<PendingRechargePayment | null> | null = null

function yuan(cents: number | null | undefined) {
  return `￥${((cents ?? 0) / 100).toFixed(2)}`
}

function fmtDate(value: string | null | undefined) {
  if (!value) return "-"
  return new Date(value).toLocaleString("zh-CN", { hour12: false })
}

function fetchFinancePrimary(currentUser: User | null) {
  const now = Date.now()
  if (primaryCache && now - primaryCache.at < BOOTSTRAP_CACHE_MS) {
    return Promise.resolve(primaryCache.data)
  }
  if (primaryPromise) return primaryPromise

  primaryPromise = Promise.allSettled([
    listRechargeOrders(30),
    listServiceOrders(),
    currentUser ? Promise.resolve<User | null>(null) : getMe().then((res) => res.data ?? null),
  ])
    .then(([rechargeRes, serviceRes, meRes]) => {
      const failedSections = [
        rechargeRes.status === "fulfilled" ? null : "充值记录",
        serviceRes.status === "fulfilled" ? null : "服务订单",
        meRes.status === "fulfilled" ? null : "用户信息",
      ].filter(Boolean) as string[]
      const data: FinancePrimaryData = {
        rechargeOrders: rechargeRes.status === "fulfilled" ? rechargeRes.value.data ?? [] : [],
        serviceOrders: serviceRes.status === "fulfilled" ? serviceRes.value.data ?? [] : [],
        me: meRes.status === "fulfilled" ? meRes.value : null,
        ok: failedSections.length === 0,
        failedSections,
      }
      primaryCache = { at: Date.now(), data }
      return data
    })
    .finally(() => {
      primaryPromise = null
    })

  return primaryPromise
}

function fetchPendingRecharge() {
  if (pendingPromise) return pendingPromise
  pendingPromise = getPendingRecharge()
    .then((res) => res.data ?? null)
    .catch(() => null)
    .finally(() => {
      pendingPromise = null
    })
  return pendingPromise
}

function refundTag(policy: ServiceOrderRefundPolicy) {
  const meta = REFUND_TYPE_META[policy.refund_type] ?? REFUND_TYPE_META.unavailable
  return <Tag color={meta.color}>{meta.label}</Tag>
}

function resourceStatusTag(status: string) {
  const meta = RESOURCE_STATUS_META[status] ?? { label: status, color: "default" }
  return <Tag color={meta.color}>{meta.label}</Tag>
}

function latestAction(actions: UpstreamActionLog[]) {
  return [...actions].sort((a, b) => b.id - a.id)[0] ?? null
}

function resourceStatusFromAction(action: UpstreamActionLog | null) {
  if (!action) return "none"
  if (["submitted", "running"].includes(action.status)) return "running"
  if (action.status === "failed") return "failed"
  if (action.status === "manual_handled") return "manual_handled"
  if (action.status === "ignored") return "ignored"
  return "finished"
}

function resourceStatusFromOrder(order: ServiceOrder) {
  return order.refund?.resource_status || resourceStatusFromAction(latestAction(order.upstream_actions || []))
}

function unsubscribeMessage(status?: string) {
  if (status === "running") return "退订已提交，资源处理中"
  if (status === "failed") return "退订已提交，资源处理异常，客服将介入"
  return "退订已处理"
}

export default function Finance() {
  const { user, setUser } = useAuth()
  const [rechargeOrders, setRechargeOrders] = useState<RechargeOrder[]>([])
  const [serviceOrders, setServiceOrders] = useState<ServiceOrder[]>([])
  const [rechargeLoading, setRechargeLoading] = useState(true)
  const [serviceLoading, setServiceLoading] = useState(true)
  const [activeTab, setActiveTab] = useState("recharge")
  const [amount, setAmount] = useState("")
  const [amountError, setAmountError] = useState("")
  const [paying, setPaying] = useState(false)
  const [paymentOptions, setPaymentOptions] = useState<RechargePaymentOption[]>([])
  const [paymentModalOpen, setPaymentModalOpen] = useState(false)
  const [pendingRechargeAmount, setPendingRechargeAmount] = useState<number | null>(null)
  const [creatingPaymentPlugin, setCreatingPaymentPlugin] = useState<string | null>(null)
  const [pendingQrcode, setPendingQrcode] = useState<string | null>(null)
  const [pendingPayUrl, setPendingPayUrl] = useState<string | null>(null)
  const [pollingNo, setPollingNo] = useState<string | null>(null)
  const [pollStatus, setPollStatus] = useState<"pending" | "paid" | "failed" | null>(null)
  const [unsubscribingId, setUnsubscribingId] = useState<number | null>(null)
  const pollTimer = useRef<ReturnType<typeof setInterval> | null>(null)
  const pollCount = useRef(0)

  const loadRechargeOrders = useCallback(async (silent = false) => {
    if (!silent) setRechargeLoading(true)
    try {
      const [ordersRes, meRes] = await Promise.all([listRechargeOrders(30), getMe()])
      setRechargeOrders(ordersRes.data ?? [])
      if (meRes.data) setUser(meRes.data)
    } catch {
      if (!silent) toast.error("充值记录加载失败")
    } finally {
      setRechargeLoading(false)
    }
  }, [setUser])

  const loadServiceOrders = useCallback(async (silent = false) => {
    if (!silent) setServiceLoading(true)
    try {
      const res = await listServiceOrders()
      setServiceOrders(res.data ?? [])
    } catch {
      if (!silent) toast.error("服务订单加载失败")
    } finally {
      setServiceLoading(false)
    }
  }, [])

  const loadPaymentOptions = useCallback(async () => {
    try {
      const res = await listRechargePaymentOptions()
      const items = res.data ?? []
      setPaymentOptions(items)
      return items
    } catch {
      toast.error("支付方式加载失败")
      return []
    }
  }, [])

  const refreshAll = useCallback(async () => {
    await Promise.all([loadRechargeOrders(true), loadServiceOrders(true)])
  }, [loadRechargeOrders, loadServiceOrders])

  const stopPoll = useCallback(() => {
    if (pollTimer.current) {
      clearInterval(pollTimer.current)
      pollTimer.current = null
    }
    pollCount.current = 0
  }, [])

  const startPoll = useCallback(
    (outTradeNo: string) => {
      setPollingNo(outTradeNo)
      setPollStatus("pending")
      pollCount.current = 0

      pollTimer.current = setInterval(async () => {
        pollCount.current += 1
        if (pollCount.current > 60) {
          stopPoll()
          setPollStatus("failed")
          return
        }

        try {
          const res = await pollRechargeStatus(outTradeNo)
          if (res.data?.paid) {
            stopPoll()
            setPollStatus("paid")
            setPendingQrcode(null)
            setPendingPayUrl(null)
            const meRes = await getMe()
            if (meRes.data) setUser(meRes.data)
            await loadRechargeOrders(true)
            toast.success("充值成功，余额已到账")
          } else if (res.data?.status === "expired" || res.data?.status === "closed") {
            stopPoll()
            setPollStatus("failed")
            setPendingPayUrl(null)
          }
        } catch {
          // Keep polling through transient network errors.
        }
      }, 5000)
    },
    [loadRechargeOrders, setUser, stopPoll],
  )

  useEffect(() => {
    let mounted = true

    setRechargeLoading(true)
    setServiceLoading(true)
    fetchFinancePrimary(user)
      .then((data) => {
        if (!mounted) return
        setRechargeOrders(data.rechargeOrders)
        setServiceOrders(data.serviceOrders)
        if (data.me) setUser(data.me)
        if (!data.ok) {
          toast.error(`财务数据加载不完整：${data.failedSections.join("、") || "未知接口"}，请刷新重试`)
        }
      })
      .finally(() => {
        if (!mounted) return
        setRechargeLoading(false)
        setServiceLoading(false)
      })

    fetchPendingRecharge().then((pending) => {
      if (!mounted || !pending) return
      setPendingQrcode(pending.qrcode)
      setPendingPayUrl(pending.payurl || pending.urlscheme)
      startPoll(pending.out_trade_no)
    })

    void loadPaymentOptions()

    return () => {
      mounted = false
    }
  }, [loadPaymentOptions, setUser, startPoll, user])

  useEffect(() => () => stopPoll(), [stopPoll])

  const validateAmount = (val: string): number | null => {
    const trimmed = val.trim()
    const n = Number(trimmed)
    if (!trimmed || Number.isNaN(n)) {
      setAmountError("请输入充值金额")
      return null
    }
    if (n < 0.1) {
      setAmountError("最低充值 ￥0.10")
      return null
    }
    if (n > 1000) {
      setAmountError("最高充值 ￥1000.00")
      return null
    }
    if (!/^\d+(\.\d{1,2})?$/.test(trimmed)) {
      setAmountError("最多保留两位小数")
      return null
    }
    setAmountError("")
    return n
  }

  const handleAmountChange = (val: string) => {
    setAmount(val)
    if (val) validateAmount(val)
    else setAmountError("")
  }

  const createRechargeWithPlugin = async (paymentPlugin: string) => {
    if (pendingRechargeAmount === null) return
    setCreatingPaymentPlugin(paymentPlugin)
    setPaying(true)
    try {
      const res = await createRecharge(pendingRechargeAmount, paymentPlugin)
      if (!res.data) throw new Error("创建订单失败")

      const { out_trade_no, payurl, qrcode, urlscheme } = res.data
      const url = payurl || urlscheme
      setPaymentModalOpen(false)
      setPendingRechargeAmount(null)
      if (qrcode && !payurl) {
        setPendingQrcode(qrcode)
        setPendingPayUrl(url)
        setAmount("")
        startPoll(out_trade_no)
        return
      }

      if (!url) {
        toast.error("支付通道未返回跳转地址，请稍后重试")
        return
      }

      const newWin = window.open(url, "_blank", "width=900,height=700,noopener,noreferrer")
      if (!newWin) window.open(url, "_blank")

      setAmount("")
      setPendingQrcode(qrcode)
      setPendingPayUrl(url)
      startPoll(out_trade_no)
    } catch (e: unknown) {
      const code = (e as { code?: string })?.code
      if (code === "ECONNABORTED") {
        const pending = await fetchPendingRecharge()
        if (pending) {
          setPaymentModalOpen(false)
          setPendingRechargeAmount(null)
          setPendingQrcode(pending.qrcode)
          setPendingPayUrl(pending.payurl || pending.urlscheme)
          startPoll(pending.out_trade_no)
          toast.info("支付通道响应较慢，已恢复待支付订单，请继续完成支付")
          return
        }
        toast.error("支付通道响应超时，请稍后重试，避免短时间内重复发起")
        return
      }
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail ?? "发起支付失败，请稍后重试")
    } finally {
      setPaying(false)
      setCreatingPaymentPlugin(null)
    }
  }

  const handlePay = async () => {
    const n = validateAmount(amount)
    if (n === null) return

    const options = paymentOptions.length ? paymentOptions : await loadPaymentOptions()
    if (!options.length) {
      toast.error("暂无可用支付方式，请稍后再试")
      return
    }
    setPendingRechargeAmount(n)
    setPaymentModalOpen(true)
  }

  const handleUnsubscribe = (record: ServiceOrder) => {
    const policy = record.refund_policy
    if (!policy.action_allowed) return

    const meta = REFUND_TYPE_META[policy.refund_type] ?? REFUND_TYPE_META.unavailable
    Modal.confirm({
      title: meta.label,
      okText: "确认退订",
      cancelText: "取消",
      okButtonProps: { danger: policy.refund_amount <= 0 },
      content: (
        <Space direction="vertical" size={8} style={{ width: "100%" }}>
          <Text>订单：{record.out_order_no}</Text>
          <Text>退款金额：<Text strong>{yuan(policy.refund_amount)}</Text></Text>
          <Text type={policy.points_claimed ? "danger" : "secondary"}>{policy.reason}</Text>
        </Space>
      ),
      onOk: async () => {
        setUnsubscribingId(record.id)
        try {
          const res = await unsubscribeOrder(record.id)
          const meRes = await getMe()
          if (meRes.data) setUser(meRes.data)
          await loadServiceOrders(true)
          toast.success(unsubscribeMessage(res.data?.refund.resource_status))
        } catch (e: unknown) {
          const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
          toast.error(detail ?? "退订失败，请稍后重试")
          throw e
        } finally {
          setUnsubscribingId(null)
        }
      },
    })
  }

  const balance = user?.balance ?? 0
  const paidRechargeCount = rechargeOrders.filter((item) => item.status === "paid").length
  const pendingRechargeCount = rechargeOrders.filter((item) => item.status === "pending").length
  const refundableCount = serviceOrders.filter((item) => item.refund_policy.action_allowed).length

  const rechargeColumns: TableColumnsType<RechargeOrder> = [
    {
      title: "订单号",
      dataIndex: "out_trade_no",
      render: (value: string) => <Text code>{value}</Text>,
    },
    {
      title: "渠道",
      dataIndex: "channel",
      render: (value: string) => CHANNEL_LABEL[value] ?? value,
    },
    {
      title: "金额",
      dataIndex: "amount",
      align: "right",
      render: (value: number) => <Text strong>￥{Number(value).toFixed(2)}</Text>,
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (value: RechargeOrder["status"]) => {
        const meta = RECHARGE_STATUS_META[value] ?? RECHARGE_STATUS_META.pending
        return <Tag color={meta.color} icon={meta.icon}>{meta.label}</Tag>
      },
    },
    {
      title: "时间",
      dataIndex: "created_at",
      render: (value: string) => <Text type="secondary">{fmtDate(value)}</Text>,
    },
  ]

  const serviceColumns: TableColumnsType<ServiceOrder> = [
    {
      title: "订单",
      dataIndex: "out_order_no",
      width: 210,
      render: (value: string) => <Text code>{value}</Text>,
    },
    {
      title: "实付",
      dataIndex: "paid_amount",
      width: 110,
      align: "right",
      render: (value: number) => <Text strong>{yuan(value)}</Text>,
    },
    {
      title: "积分",
      dataIndex: "points_claimed",
      width: 110,
      render: (value: boolean) => value ? <Tag color="red">已领取</Tag> : <Tag color="blue">未领取</Tag>,
    },
    {
      title: "退订规则",
      dataIndex: "refund_policy",
      width: 190,
      render: (policy: ServiceOrderRefundPolicy) => (
        <Space direction="vertical" size={2}>
          {refundTag(policy)}
          <Text type="secondary" style={{ fontSize: 12 }}>{policy.reason}</Text>
        </Space>
      ),
    },
    {
      title: "预计退款",
      dataIndex: ["refund_policy", "refund_amount"],
      width: 110,
      align: "right",
      render: (_value, record) => <Text strong>{yuan(record.refund_policy.refund_amount)}</Text>,
    },
    {
      title: "资源进度",
      width: 150,
      render: (_value, record) => {
        const action = latestAction(record.upstream_actions || [])
        const resourceStatus = resourceStatusFromOrder(record)
        if (resourceStatus === "none" && !action) return <Text type="secondary">-</Text>
        return (
          <Space direction="vertical" size={2}>
            {resourceStatusTag(resourceStatus)}
            <Text type="secondary" style={{ fontSize: 12 }}>
              {record.refund?.resource_error || (action ? ACTION_TYPE_LABEL[action.action_type] ?? action.action_type : "-")}
            </Text>
          </Space>
        )
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 100,
      render: (value: string) => {
        const meta = ORDER_STATUS_META[value] ?? { label: value, color: "default" }
        return <Tag color={meta.color}>{meta.label}</Tag>
      },
    },
    {
      title: "时间",
      dataIndex: "created_at",
      width: 170,
      render: (value: string | null) => <Text type="secondary">{fmtDate(value)}</Text>,
    },
    {
      title: "操作",
      key: "action",
      width: 110,
      fixed: "right",
      render: (_value, record) => (
        <Button
          size="small"
          icon={<RollbackOutlined />}
          disabled={!record.refund_policy.action_allowed}
          loading={unsubscribingId === record.id}
          onClick={() => handleUnsubscribe(record)}
        >
          退订
        </Button>
      ),
    },
  ]

  const rechargeContent = (
    <Space direction="vertical" size={20} style={{ width: "100%" }}>
      <Card variant="outlined" styles={{ body: { padding: 24 } }}>
        <Row gutter={[24, 24]} align="middle">
          <Col xs={24} lg={10}>
            <Space direction="vertical" size={6}>
              <Text type="secondary">账户可用余额</Text>
              <Title level={1} style={{ margin: 0, lineHeight: 1.1 }}>{yuan(balance)}</Title>
              <Text type="secondary">余额可用于购买、续费和升级云服务。</Text>
            </Space>
          </Col>
          <Col xs={24} sm={8} lg={4}>
            <Statistic title="充值记录" value={rechargeOrders.length} suffix="笔" />
          </Col>
          <Col xs={24} sm={8} lg={4}>
            <Statistic title="已到账" value={paidRechargeCount} suffix="笔" />
          </Col>
          <Col xs={24} sm={8} lg={4}>
            <Statistic title="待支付" value={pendingRechargeCount} suffix="笔" />
          </Col>
        </Row>
      </Card>

      <Row gutter={[16, 16]} align="stretch">
        <Col xs={24} xl={15}>
          <Card title={<Space><WalletOutlined /> 在线充值</Space>} variant="outlined" styles={{ body: { minHeight: 332 } }}>
            <Space direction="vertical" size={18} style={{ width: "100%" }}>
              <div>
                <Text strong>选择充值金额</Text>
                <Row gutter={[10, 10]} style={{ marginTop: 12 }}>
                  {PRESET_AMOUNTS.map((value) => (
                    <Col xs={8} sm={4} key={value}>
                      <Button
                        block
                        type={amount === String(value) ? "primary" : "default"}
                        onClick={() => { setAmount(String(value)); setAmountError("") }}
                      >
                        ￥{value}
                      </Button>
                    </Col>
                  ))}
                </Row>
              </div>

              <div>
                <Text strong>自定义金额</Text>
                <div style={{ marginTop: 12 }}>
                  <Input
                    type="number"
                    value={amount}
                    placeholder="请输入 0.10 ~ 1000.00"
                    min={0.1}
                    max={1000}
                    step={0.01}
                    prefix="￥"
                    onChange={(event) => handleAmountChange(event.target.value)}
                  />
                </div>
                <div style={{ marginTop: 8 }}>
                  {amountError
                    ? <Text type="danger">{amountError}</Text>
                    : <Text type="secondary">支持支付宝 / 微信，充值成功后余额实时到账。</Text>}
                </div>
              </div>

              <Space wrap>
                <Button
                  type="primary"
                  size="large"
                  icon={<CreditCardOutlined />}
                  loading={paying}
                  disabled={!amount || !!amountError}
                  onClick={handlePay}
                >
                  前往支付
                </Button>
                <Text type="secondary">单笔充值范围：￥0.10 - ￥1000.00</Text>
              </Space>
            </Space>
          </Card>
        </Col>

        <Col xs={24} xl={9}>
          <Card
            title={<Space><CreditCardOutlined /> 支付状态</Space>}
            variant="outlined"
            styles={{ body: { minHeight: 332, display: "flex", alignItems: "center", justifyContent: "center" } }}
          >
            {pendingQrcode ? (
              <Space direction="vertical" align="center" size={14} style={{ width: "100%" }}>
                <Text strong>扫码完成支付</Text>
                <QRCode value={pendingQrcode} size={188} />
                <Text type="secondary">系统正在轮询支付结果，请勿重复下单。</Text>
                <Space>
                  {pendingPayUrl && (
                    <Button size="small" type="primary" onClick={() => window.open(pendingPayUrl, "_blank")}>
                      打开支付页
                    </Button>
                  )}
                  <Button size="small" onClick={() => setPendingQrcode(null)}>关闭二维码</Button>
                </Space>
              </Space>
            ) : pollingNo ? (
              <Alert
                showIcon
                style={{ width: "100%" }}
                type={pollStatus === "paid" ? "success" : pollStatus === "failed" ? "error" : "info"}
                message={
                  pollStatus === "paid"
                    ? "充值成功"
                    : pollStatus === "failed"
                      ? "支付未完成"
                      : "正在等待支付结果"
                }
                description={(
                  <Space direction="vertical" size={8}>
                    <Text type="secondary">订单号：{pollingNo}</Text>
                    <Space>
                      {pendingPayUrl && (
                        <Button size="small" type="primary" onClick={() => window.open(pendingPayUrl, "_blank")}>
                          重新打开支付页
                        </Button>
                      )}
                      <Button size="small" onClick={() => { stopPoll(); setPollingNo(null); setPollStatus(null) }}>
                        关闭状态
                      </Button>
                    </Space>
                  </Space>
                )}
              />
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无待处理支付">
                <Text type="secondary">发起充值后，二维码或支付状态会显示在这里。</Text>
              </Empty>
            )}
          </Card>
        </Col>
      </Row>

      <Card title={<Space><HistoryOutlined /> 充值记录</Space>} variant="outlined">
        <Table
          rowKey="id"
          loading={rechargeLoading}
          dataSource={rechargeOrders}
          pagination={{ pageSize: 10, showSizeChanger: false }}
          columns={rechargeColumns}
        />
      </Card>
    </Space>
  )

  const serviceRefundPolicy = serviceOrders[0]?.refund_policy
  const fullRefundSuffix = serviceRefundPolicy?.full_refund_unlimited
    ? " / 不限"
    : `/ ${serviceRefundPolicy?.full_refund_limit ?? 0}`

  const serviceContent = (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      <Row gutter={[16, 16]}>
        <Col xs={24} sm={8}>
          <Card variant="outlined"><Statistic title="服务订单" value={serviceOrders.length} suffix="笔" /></Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card variant="outlined"><Statistic title="可退订" value={refundableCount} suffix="笔" /></Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card variant="outlined"><Statistic title="全额退订次数" value={serviceRefundPolicy?.full_refund_used ?? 0} suffix={fullRefundSuffix} /></Card>
        </Col>
      </Row>

      <Alert
        type="info"
        showIcon
        message="未领取积分的订单可按规则退订；已领取积分的订单退订不退款。"
      />

      <Card title={<Space><HistoryOutlined /> 服务订单</Space>} variant="outlined">
        <Table
          rowKey="id"
          loading={serviceLoading}
          dataSource={serviceOrders}
          pagination={{ pageSize: 10, showSizeChanger: false }}
          columns={serviceColumns}
          scroll={{ x: 1180 }}
        />
      </Card>
    </Space>
  )

  return (
    <Space direction="vertical" size={20} style={{ width: "100%" }}>
      <Row gutter={[16, 16]} align="bottom" justify="space-between">
        <Col>
          <Title level={3} style={{ margin: 0 }}>财务管理</Title>
          <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
            管理账户余额、充值记录、服务订单和退订退款。
          </Paragraph>
        </Col>
        <Col>
          <Button
            icon={<ReloadOutlined />}
            loading={activeTab === "recharge" ? rechargeLoading : serviceLoading}
            onClick={refreshAll}
          >
            刷新数据
          </Button>
        </Col>
      </Row>

      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={[
          { key: "recharge", label: "充值管理", children: rechargeContent },
          { key: "finance", label: "财务管理", children: serviceContent },
        ]}
      />

      <Modal
        title="选择支付方式"
        open={paymentModalOpen}
        onCancel={() => {
          if (paying) return
          setPaymentModalOpen(false)
          setPendingRechargeAmount(null)
        }}
        footer={null}
        destroyOnHidden
      >
        <Space direction="vertical" size={12} style={{ width: "100%" }}>
          {paymentOptions.map((option) => (
            <Card size="small" variant="outlined" key={option.id}>
              <Row gutter={[12, 12]} align="middle" justify="space-between">
                <Col flex="auto">
                  <Space direction="vertical" size={2}>
                    <Space wrap>
                      <Text strong>{option.name}</Text>
                      <Tag color="blue">{option.method_label}</Tag>
                    </Space>
                    <Text type="secondary">{option.description || "在线支付通道"}</Text>
                  </Space>
                </Col>
                <Col>
                  <Button
                    type="primary"
                    loading={creatingPaymentPlugin === option.id}
                    disabled={paying && creatingPaymentPlugin !== option.id}
                    onClick={() => void createRechargeWithPlugin(option.id)}
                  >
                    选择
                  </Button>
                </Col>
              </Row>
            </Card>
          ))}
        </Space>
      </Modal>
    </Space>
  )
}
