import { useCallback, useEffect, useMemo, useState } from "react"
import { useNavigate, useParams } from "react-router-dom"
import {
  ArrowLeftOutlined,
  CloudServerOutlined,
  DeleteOutlined,
  ExportOutlined,
  FileSearchOutlined,
  PauseCircleOutlined,
  PlayCircleOutlined,
  PlusOutlined,
  PoweroffOutlined,
  ReloadOutlined,
  SaveOutlined,
  SyncOutlined,
  WalletOutlined,
} from "@ant-design/icons"
import {
  Alert,
  Button,
  Card,
  Col,
  Descriptions,
  Empty,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Result,
  Row,
  Select,
  Skeleton,
  Space,
  Statistic,
  Switch,
  Table,
  Tabs,
  Tag,
  Typography,
  type TableColumnsType,
} from "antd"
import {
  listAdminServiceOrders,
  unsubscribeAdminServiceOrder,
  type AdminServiceOrder,
} from "../api/service_orders"
import { toast } from "../../utils/toast"
import {
  createUserInstanceNatAcl,
  deleteUserInstanceNatAcl,
  getUserInstance,
  listUserInstanceNatAcl,
  updateUserInstanceBilling,
  type AdminInstanceNatAclItem,
  type AdminUserInstanceDetail,
} from "../api/user"
import {
  deleteAdminInstance,
  getAdminInstance,
  operateAdminInstancePower,
  provisionAdminInstance,
  runAdminPluginAction,
  suspendAdminInstance,
  unsuspendAdminInstance,
  type AdminInstancePowerAction,
} from "../api/instances"

const { Title, Text } = Typography

const STATUS_META: Record<string, { label: string; color: string }> = {
  active: { label: "运行中", color: "success" },
  provisioning: { label: "开通中", color: "processing" },
  provision_failed: { label: "待处理", color: "error" },
  failed: { label: "开通失败", color: "error" },
  suspended: { label: "已暂停", color: "warning" },
  terminated: { label: "已销毁", color: "default" },
}

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" },
}

interface BillingFormValues {
  cycle: string
  unit_price_yuan: number
  next_renew_amount_yuan: number
  expires_at: string | null
  auto_renew: boolean
}

interface NatAclFormValues {
  name: string
  ext_port?: number | null
  int_port: number
  protocol: 1 | 2 | 3
}

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

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

function yuanToCents(value: number | null | undefined) {
  return Math.round(Number(value || 0) * 100)
}

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

function toLocalInput(value: string | null | undefined) {
  if (!value) return ""
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ""
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
  return local.toISOString().slice(0, 16)
}

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

function tag(meta: Record<string, { label: string; color: string }>, value: string | null | undefined) {
  const item = meta[value || ""] ?? { label: value || "未知", color: "default" }
  return <Tag color={item.color}>{item.label}</Tag>
}

function userLabel(instance: AdminUserInstanceDetail) {
  return instance.user.nickname || instance.user.username || instance.user.email || `用户 #${instance.user.id}`
}

function externalAddress(natHostIp: string | null, port: number | null | undefined) {
  if (!natHostIp || !port) return "-"
  return `${natHostIp}:${port}`
}

function internalAddress(record: AdminInstanceNatAclItem) {
  const ip = record.int_ip || ""
  if (ip && record.int_port) return `${ip}:${record.int_port}`
  if (ip) return ip
  if (record.int_port) return `内网端口 ${record.int_port}`
  return "-"
}

function protocolLabel(value: number | null | undefined) {
  if (value === 1) return "TCP"
  if (value === 2) return "UDP"
  if (value === 3) return "TCP+UDP"
  return "-"
}

function orderUserContent(order: AdminServiceOrder) {
  const content = order.content?.length ? order.content : ["服务订单"]
  return (
    <Space orientation="vertical" size={2}>
      {content.map((item, index) => (
        <Text key={`${order.id}-${index}`}>{item}</Text>
      ))}
      {order.instances?.length ? (
        <Text type="secondary" style={{ fontSize: 12 }}>
          {order.instances.map((item) => item.main_ip || item.hostname || `实例 #${item.id}`).join("、")}
        </Text>
      ) : null}
    </Space>
  )
}

export default function AdminInstanceDetail() {
  const navigate = useNavigate()
  const params = useParams<{ userId?: string; instanceId: string }>()
  const routeUserId = params.userId ? Number(params.userId) : null
  const instanceId = Number(params.instanceId)
  const [billingForm] = Form.useForm<BillingFormValues>()
  const [natForm] = Form.useForm<NatAclFormValues>()

  const [loading, setLoading] = useState(true)
  const [ordersLoading, setOrdersLoading] = useState(false)
  const [actionLoading, setActionLoading] = useState<string | null>(null)
  const [instance, setInstance] = useState<AdminUserInstanceDetail | null>(null)
  const [orders, setOrders] = useState<AdminServiceOrder[]>([])
  const [natLoading, setNatLoading] = useState(false)
  const [natSaving, setNatSaving] = useState(false)
  const [natModalOpen, setNatModalOpen] = useState(false)
  const [natDeletingId, setNatDeletingId] = useState<number | null>(null)
  const [natItems, setNatItems] = useState<AdminInstanceNatAclItem[]>([])
  const [natHostIp, setNatHostIp] = useState<string | null>(null)
  const [natMeta, setNatMeta] = useState({ total: 0, total_page: 0, page: 1, per_page: 20 })
  const [natPage, setNatPage] = useState(1)
  const [natPageSize, setNatPageSize] = useState(20)

  const reload = useCallback(async () => {
    setLoading(true)
    try {
      const res = routeUserId
        ? await getUserInstance(routeUserId, instanceId)
        : await getAdminInstance(instanceId)
      setInstance(res.data ?? null)
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载实例详情失败")
      setInstance(null)
    } finally {
      setLoading(false)
    }
  }, [instanceId, routeUserId])

  const reloadOrders = useCallback(async () => {
    setOrdersLoading(true)
    try {
      const res = await listAdminServiceOrders({ instance_id: instanceId, limit: 200 })
      setOrders(res.data ?? [])
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载关联订单失败")
    } finally {
      setOrdersLoading(false)
    }
  }, [instanceId])

  const reloadNat = useCallback(async () => {
    const ownerUserId = instance?.user.id ?? routeUserId
    if (!ownerUserId) return
    setNatLoading(true)
    try {
      const res = await listUserInstanceNatAcl(ownerUserId, instanceId, {
        page: natPage,
        per_page: natPageSize,
        orderby: "id",
        sort: "desc",
        list_type: "page",
      })
      const data = res.data
      setNatItems(data?.list ?? [])
      setNatMeta(data?.meta ?? { total: 0, total_page: 0, page: natPage, per_page: natPageSize })
      setNatHostIp(data?.nat_host_ip ?? null)
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载 NAT 转发列表失败")
      setNatItems([])
      setNatHostIp(null)
      setNatMeta({ total: 0, total_page: 0, page: natPage, per_page: natPageSize })
    } finally {
      setNatLoading(false)
    }
  }, [instance?.user.id, instanceId, natPage, natPageSize, routeUserId])

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

  const showNatTab = !!instance && !instance.main_ip && instance.status === "active"

  useEffect(() => {
    if (showNatTab) void reloadNat()
  }, [reloadNat, showNatTab])

  useEffect(() => {
    if (!instance) return
    billingForm.setFieldsValue({
      cycle: instance.cycle,
      unit_price_yuan: centsToYuan(instance.unit_price),
      next_renew_amount_yuan: centsToYuan(instance.next_renew_amount),
      expires_at: toLocalInput(instance.expires_at),
      auto_renew: Number(instance.auto_renew || 0) === 1,
    })
  }, [billingForm, instance])

  const connectionAddress = useMemo(() => {
    if (instance?.main_ip) return instance.ssh_port ? `${instance.main_ip}:${instance.ssh_port}` : instance.main_ip
    if (!natHostIp) return null
    const linuxRule = natItems.find((item) => Number(item.int_port) === 22)
    const windowsRule = natItems.find((item) => Number(item.int_port) === 3389)
    const rule = linuxRule ?? windowsRule
    return rule?.ext_port ? `${natHostIp}:${rule.ext_port}` : null
  }, [instance, natHostIp, natItems])

  const stats = useMemo(() => ({
    totalOrders: orders.length,
    refundable: orders.filter((item) => item.refund_policy?.action_allowed).length,
    paidAmount: orders.reduce((sum, item) => sum + Number(item.paid_amount || 0), 0),
    refundAmount: orders.reduce((sum, item) => sum + Number(item.refund?.refund_amount || 0), 0),
  }), [orders])

  const natLimit = Number(instance?.nat_acl_limit || 0)
  const natLimitReached = natLimit > 0 && natMeta.total >= natLimit

  const refreshAll = async () => {
    await Promise.all([reload(), reloadOrders()])
    if (showNatTab) await reloadNat()
  }

  const openCreateNat = () => {
    natForm.setFieldsValue({ name: "", ext_port: null, int_port: 22, protocol: 1 })
    setNatModalOpen(true)
  }

  const handleCreateNat = async () => {
    if (!instance) return
    const values = await natForm.validateFields()
    setNatSaving(true)
    try {
      await createUserInstanceNatAcl(instance.user.id, instance.id, {
        name: values.name.trim(),
        ext_port: values.ext_port ?? null,
        int_port: values.int_port,
        protocol: values.protocol,
      })
      toast.success("NAT 转发已添加")
      setNatModalOpen(false)
      setNatPage(1)
      await reloadNat()
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "添加 NAT 转发失败")
    } finally {
      setNatSaving(false)
    }
  }

  const handleDeleteNat = async (record: AdminInstanceNatAclItem) => {
    if (!instance || !record.id) return
    setNatDeletingId(record.id)
    try {
      await deleteUserInstanceNatAcl(instance.user.id, instance.id, record.id)
      toast.success("NAT 转发已删除")
      await reloadNat()
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "删除 NAT 转发失败")
    } finally {
      setNatDeletingId(null)
    }
  }

  const copyExternalAddress = async (value: string) => {
    try {
      await navigator.clipboard.writeText(value)
      toast.success("已复制外网地址")
    } catch {
      toast.error("复制失败")
    }
  }

  const openUpstreamConsole = () => {
    if (!instance?.upstream_console_url) {
      toast.error("缺少主控地址或上游实例 ID")
      return
    }
    const opened = window.open(instance.upstream_console_url, "_blank", "noopener,noreferrer")
    if (opened) opened.opener = null
  }

  const runManageAction = async (key: string, label: string, fn: () => Promise<unknown>) => {
    if (!instance) return
    setActionLoading(key)
    try {
      await fn()
      toast.success(`${label}指令已下发`)
      await refreshAll()
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || `${label}失败`)
    } finally {
      setActionLoading(null)
    }
  }

  const runPluginAction = async (action: string, label: string, payload?: Record<string, unknown>) => {
    if (!instance) return
    setActionLoading(`plugin:${action}`)
    try {
      const res = await runAdminPluginAction(instance.id, action, payload)
      const message = typeof res.data?.message === "string" ? res.data.message : `${label}执行成功`
      toast.success(message)
      await refreshAll()
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || `${label}失败`)
    } finally {
      setActionLoading(null)
    }
  }

  const confirmManageAction = (
    key: string,
    label: string,
    fn: () => Promise<unknown>,
    danger = false,
  ) => {
    if (!instance) return
    Modal.confirm({
      title: `确认${label}实例？`,
      okText: label,
      cancelText: "取消",
      okButtonProps: { danger },
      content: (
        <Space orientation="vertical" size={4}>
          <Text>{instance.hostname || instance.alias || `实例 #${instance.id}`}</Text>
          <Text type="secondary">用户：{userLabel(instance)}</Text>
        </Space>
      ),
      onOk: () => runManageAction(key, label, fn),
    })
  }

  const confirmPowerAction = (action: AdminInstancePowerAction, label: string, danger = false) => {
    if (!instance) return
    confirmManageAction(
      action,
      label,
      () => operateAdminInstancePower(instance.id, action),
      danger,
    )
  }

  const saveBilling = async () => {
    if (!instance) return
    const values = await billingForm.validateFields()
    setActionLoading("billing")
    try {
      await updateUserInstanceBilling(instance.user.id, instance.id, {
        cycle: values.cycle.trim(),
        unit_price: yuanToCents(values.unit_price_yuan),
        next_renew_amount: yuanToCents(values.next_renew_amount_yuan),
        expires_at: toIso(values.expires_at),
        auto_renew: values.auto_renew,
      })
      toast.success("计费价格已保存")
      await reload()
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "保存计费价格失败")
    } finally {
      setActionLoading(null)
    }
  }

  const confirmUnsubscribe = (record: AdminServiceOrder) => {
    const policy = record.refund_policy
    Modal.confirm({
      title: "确认退订该订单？",
      okText: "确认退订",
      okButtonProps: { danger: true },
      cancelText: "取消",
      content: (
        <Space orientation="vertical" size={8}>
          <Text>订单号：{record.out_order_no}</Text>
          <Text>退订规则：{policy.reason}</Text>
          <Text>预计退款：<Text strong>{yuan(policy.refund_amount)}</Text></Text>
          {record.points_claimed ? <Alert type="warning" showIcon title="该订单已领取积分，退订可能不退款。" /> : null}
        </Space>
      ),
      onOk: async () => {
        setActionLoading(`unsubscribe-${record.id}`)
        try {
          const res = await unsubscribeAdminServiceOrder(record.id)
          toast.success(`退订已处理${res.data?.total_refund ? `，退款 ${yuan(res.data.total_refund)}` : ""}`)
          await refreshAll()
        } catch (error: unknown) {
          const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
          toast.error(detail || "退订失败")
          throw error
        } finally {
          setActionLoading(null)
        }
      },
    })
  }

  const orderColumns: TableColumnsType<AdminServiceOrder> = [
    {
      title: "订单号",
      dataIndex: "out_order_no",
      width: 210,
      render: (value: string) => <Text code>{value}</Text>,
    },
    {
      title: "内容",
      dataIndex: "content",
      minWidth: 260,
      render: (_value, record) => orderUserContent(record),
    },
    {
      title: "金额",
      width: 135,
      align: "right",
      render: (_value, record) => (
        <Space orientation="vertical" size={0} align="end">
          <Text strong>{yuan(record.paid_amount)}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>
            {record.refund ? `已退 ${yuan(record.refund.refund_amount)}` : `预计退 ${yuan(record.refund_policy.refund_amount)}`}
          </Text>
        </Space>
      ),
    },
    {
      title: "状态",
      width: 120,
      render: (_value, record) => (
        <Space orientation="vertical" size={4}>
          {tag(ORDER_STATUS_META, record.status)}
          {record.refund ? tag(RESOURCE_STATUS_META, record.refund.resource_status) : null}
        </Space>
      ),
    },
    {
      title: "退订规则",
      width: 190,
      render: (_value, record) => (
        <Space orientation="vertical" size={2}>
          {tag(REFUND_TYPE_META, record.refund_policy.refund_type)}
          <Text type="secondary" style={{ fontSize: 12 }}>{record.refund_policy.reason}</Text>
        </Space>
      ),
    },
    { title: "创建时间", dataIndex: "created_at", width: 170, render: fmtDate },
    {
      title: "操作",
      width: 130,
      fixed: "right",
      render: (_value, record) => (
        <Button
          danger
          size="small"
          disabled={!record.refund_policy.action_allowed}
          loading={actionLoading === `unsubscribe-${record.id}`}
          onClick={() => confirmUnsubscribe(record)}
        >
          退订
        </Button>
      ),
    },
  ]

  const natColumns: TableColumnsType<AdminInstanceNatAclItem> = [
    { title: "名称", dataIndex: "name", render: (value) => value || "-" },
    {
      title: "外网地址",
      render: (_value, record) => {
        const value = externalAddress(natHostIp, record.ext_port)
        return value === "-" ? "-" : (
          <Text
            style={{ color: "#1677ff", cursor: "pointer" }}
            onClick={() => void copyExternalAddress(value)}
          >
            {value}
          </Text>
        )
      },
    },
    { title: "内网地址", render: (_value, record) => internalAddress(record) },
    { title: "协议", render: (_value, record) => protocolLabel(record.protocol) },
    {
      title: "操作",
      width: 110,
      render: (_value, record) => (
        <Popconfirm
          title="删除 NAT 转发？"
          okText="删除"
          cancelText="取消"
          okButtonProps={{ danger: true }}
          disabled={!record.id}
          onConfirm={() => void handleDeleteNat(record)}
        >
          <Button size="small" danger disabled={!record.id} loading={natDeletingId === record.id}>
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ]

  if (loading) return <Skeleton active paragraph={{ rows: 12 }} />

  if (!instance) {
    return (
      <Result
        status="404"
        title="实例不存在"
        extra={<Button onClick={() => navigate(-1)}>返回</Button>}
      />
    )
  }

  const backPath = routeUserId ? `/admin/users/${instance.user.id}` : "/admin/instances"
  const upstreamActionDisabled = !instance.upstream_id || instance.status === "terminated"
  const canSuspend = instance.status === "active" && !!instance.upstream_id
  const canUnsuspend = instance.status === "suspended" && !!instance.upstream_id
  const canProvision = instance.status === "provisioning" || instance.status === "provision_failed"

  const tabs = [
    {
      key: "server",
      label: "服务器管理",
      children: (
        <Row gutter={[16, 16]}>
          <Col xs={24} lg={14}>
            <Card variant="outlined" title="主控入口">
              <Space orientation="vertical" size={16} style={{ width: "100%" }}>
                <Alert
                  type="info"
                  showIcon
                  title="常用实例动作可直接在本站下发；复杂上游参数仍可打开主控实例页处理。"
                />
                <Descriptions column={1} bordered size="small">
                  <Descriptions.Item label="主控节点">{instance.cloud_server_name || `#${instance.cloud_server_id || "-"}`}</Descriptions.Item>
                  <Descriptions.Item label="主控地址">{instance.cloud_server_base_url || "-"}</Descriptions.Item>
                  <Descriptions.Item label="上游实例 ID">{instance.upstream_id || "-"}</Descriptions.Item>
                  <Descriptions.Item label="跳转地址">
                    {instance.upstream_console_url ? <Text copyable>{instance.upstream_console_url}</Text> : "-"}
                  </Descriptions.Item>
                </Descriptions>
                <Button
                  type="primary"
                  icon={<ExportOutlined />}
                  disabled={!instance.upstream_console_url}
                  onClick={openUpstreamConsole}
                >
                  打开主控实例页
                </Button>
                <Space wrap>
                  <Button
                    icon={<PlayCircleOutlined />}
                    disabled={upstreamActionDisabled}
                    loading={actionLoading === "power-on"}
                    onClick={() => confirmPowerAction("power-on", "开机")}
                  >
                    开机
                  </Button>
                  <Button
                    icon={<ReloadOutlined />}
                    disabled={upstreamActionDisabled}
                    loading={actionLoading === "reboot"}
                    onClick={() => confirmPowerAction("reboot", "重启")}
                  >
                    重启
                  </Button>
                  <Button
                    danger
                    icon={<PoweroffOutlined />}
                    disabled={upstreamActionDisabled}
                    loading={actionLoading === "shutdown"}
                    onClick={() => confirmPowerAction("shutdown", "关机", true)}
                  >
                    关机
                  </Button>
                  <Button
                    danger
                    icon={<PoweroffOutlined />}
                    disabled={upstreamActionDisabled}
                    loading={actionLoading === "hard-shutdown"}
                    onClick={() => confirmPowerAction("hard-shutdown", "强制关机", true)}
                  >
                    强制关机
                  </Button>
                  <Button
                    icon={<PauseCircleOutlined />}
                    disabled={!canSuspend}
                    loading={actionLoading === "suspend"}
                    onClick={() => confirmManageAction("suspend", "暂停", () => suspendAdminInstance(instance.id))}
                  >
                    暂停
                  </Button>
                  <Button
                    icon={<PlayCircleOutlined />}
                    disabled={!canUnsuspend}
                    loading={actionLoading === "unsuspend"}
                    onClick={() => confirmManageAction("unsuspend", "解除暂停", () => unsuspendAdminInstance(instance.id))}
                  >
                    解除暂停
                  </Button>
                  <Button
                    icon={<SyncOutlined />}
                    disabled={!canProvision}
                    loading={actionLoading === "provision"}
                    onClick={() => confirmManageAction("provision", "重新开通", () => provisionAdminInstance(instance.id))}
                  >
                    重新开通
                  </Button>
                  <Button
                    danger
                    icon={<DeleteOutlined />}
                    disabled={instance.status === "terminated"}
                    loading={actionLoading === "delete"}
                    onClick={() => confirmManageAction("delete", "删除", () => deleteAdminInstance(instance.id), true)}
                  >
                    删除实例
                  </Button>
                </Space>
              </Space>
            </Card>

            {/* 插件管理操作 */}
            {(instance.plugin_manage_actions?.length ?? 0) > 0 && (
              <Card variant="outlined" title="插件管理操作" style={{ marginTop: 16 }}>
                <Space wrap>
                  {instance.plugin_manage_actions!.map((action) => {
                    const btn = (
                      <Button
                        key={action.key}
                        danger={action.style === "danger"}
                        type={action.style === "primary" ? "primary" : "default"}
                        loading={actionLoading === `plugin:${action.key}`}
                        disabled={instance.status === "terminated"}
                        onClick={action.confirm ? undefined : () => runPluginAction(action.key, action.label)}
                      >
                        {action.label}
                        {action.audience === "admin" ? null : null}
                      </Button>
                    )
                    return action.confirm ? (
                      <Popconfirm
                        key={action.key}
                        title={`确认执行 ${action.label}？`}
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => runPluginAction(action.key, action.label)}
                      >
                        {btn}
                      </Popconfirm>
                    ) : btn
                  })}
                </Space>
              </Card>
            )}

          </Col>
          <Col xs={24} lg={10}>
            <Card variant="outlined" title="实例摘要">
              <Descriptions column={1} size="small">
                <Descriptions.Item label="本地实例 ID">#{instance.id}</Descriptions.Item>
                <Descriptions.Item label="状态">{tag(STATUS_META, instance.status)}</Descriptions.Item>
                <Descriptions.Item label="产品">{instance.product_name}</Descriptions.Item>
                <Descriptions.Item label="线路">{instance.product_group_name || "-"}</Descriptions.Item>
                <Descriptions.Item label="连接地址">{connectionAddress || "-"}</Descriptions.Item>
                <Descriptions.Item label="到期时间">{fmtDate(instance.expires_at)}</Descriptions.Item>
              </Descriptions>
            </Card>
          </Col>
        </Row>
      ),
    },
    {
      key: "billing",
      label: "计费价格",
      children: (
        <Row gutter={[16, 16]}>
          <Col xs={24} lg={10}>
            <Card variant="outlined" title="价格与续费">
              <Form form={billingForm} layout="vertical">
                <Form.Item name="cycle" label="计费周期" rules={[{ required: true, message: "请输入计费周期" }]}>
                  <Input placeholder="monthly / yearly" />
                </Form.Item>
                <Form.Item name="unit_price_yuan" label="周期单价（元）" rules={[{ required: true, message: "请输入周期单价" }]}>
                  <InputNumber min={0} precision={2} style={{ width: "100%" }} />
                </Form.Item>
                <Form.Item name="next_renew_amount_yuan" label="下次续费金额（元）" rules={[{ required: true, message: "请输入续费金额" }]}>
                  <InputNumber min={0} precision={2} style={{ width: "100%" }} />
                </Form.Item>
                <Form.Item name="expires_at" label="到期时间">
                  <Input type="datetime-local" />
                </Form.Item>
                <Form.Item name="auto_renew" label="自动续费" valuePropName="checked">
                  <Switch disabled={instance.status === "terminated"} />
                </Form.Item>
                <Button
                  type="primary"
                  icon={<SaveOutlined />}
                  loading={actionLoading === "billing"}
                  disabled={instance.status === "terminated"}
                  onClick={saveBilling}
                >
                  保存计费价格
                </Button>
              </Form>
            </Card>
          </Col>
          <Col xs={24} lg={14}>
            <Card variant="outlined" title="财务概览">
              <Descriptions column={2} bordered size="small">
                <Descriptions.Item label="账户余额">{yuan(instance.user.balance)}</Descriptions.Item>
                <Descriptions.Item label="自动续费">{Number(instance.auto_renew || 0) === 1 ? <Tag color="green">已开启</Tag> : <Tag>未开启</Tag>}</Descriptions.Item>
                <Descriptions.Item label="周期单价">{yuan(instance.unit_price)}</Descriptions.Item>
                <Descriptions.Item label="下次续费">{yuan(instance.next_renew_amount)}</Descriptions.Item>
                <Descriptions.Item label="关联订单">{stats.totalOrders} 笔</Descriptions.Item>
                <Descriptions.Item label="可退订">{stats.refundable} 笔</Descriptions.Item>
                <Descriptions.Item label="累计实付">{yuan(stats.paidAmount)}</Descriptions.Item>
                <Descriptions.Item label="已退款">{yuan(stats.refundAmount)}</Descriptions.Item>
              </Descriptions>
            </Card>
          </Col>
        </Row>
      ),
    },
    {
      key: "orders",
      label: "订单退订",
      children: (
        <Card
          variant="outlined"
          title="关联服务订单"
          extra={<Button icon={<FileSearchOutlined />} onClick={() => navigate("/admin/service-orders")}>订单中心</Button>}
        >
          <Table
            rowKey="id"
            loading={ordersLoading}
            columns={orderColumns}
            dataSource={orders}
            pagination={{ pageSize: 8 }}
            scroll={{ x: 1220 }}
            locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无关联订单" /> }}
          />
        </Card>
      ),
    },
    ...(showNatTab ? [{
      key: "nat",
      label: "转发管理",
      children: (
        <Space orientation="vertical" size={12} style={{ width: "100%" }}>
          <Space wrap>
            <Button type="primary" icon={<PlusOutlined />} disabled={natLimitReached} onClick={openCreateNat}>
              添加 NAT 转发
            </Button>
            <Button icon={<ReloadOutlined />} loading={natLoading} onClick={() => void reloadNat()}>
              刷新
            </Button>
            <Text type="secondary">NAT 转发限制：{natLimit > 0 ? `${natMeta.total} / ${natLimit}` : "-"}</Text>
          </Space>

          <Table
            rowKey={(record) => String(record.id ?? `${record.ext_port}-${record.int_port}-${record.name}`)}
            loading={natLoading}
            columns={natColumns}
            dataSource={natItems}
            pagination={{
              current: natPage,
              pageSize: natPageSize,
              total: natMeta.total,
              showSizeChanger: true,
              pageSizeOptions: [10, 20, 50, 100],
            }}
            onChange={(pagination) => {
              setNatPage(pagination.current || 1)
              setNatPageSize(pagination.pageSize || natPageSize)
            }}
            locale={{ emptyText: <Empty description="暂无 NAT 转发规则" /> }}
          />

          <Modal
            title="添加 NAT 转发"
            open={natModalOpen}
            okText="添加"
            cancelText="取消"
            confirmLoading={natSaving}
            onOk={handleCreateNat}
            onCancel={() => setNatModalOpen(false)}
            destroyOnHidden
          >
            <Form<NatAclFormValues> form={natForm} layout="vertical" style={{ marginTop: 20 }}>
              <Form.Item name="name" label="名称" rules={[{ required: true, message: "请输入名称" }]}>
                <Input maxLength={100} placeholder="例如 SSH" allowClear />
              </Form.Item>
              <Form.Item
                name="ext_port"
                label="外部端口"
                rules={[{
                  validator: (_, value: number | null | undefined) => (
                    value == null || ![22, 80, 443].includes(Number(value))
                      ? Promise.resolve()
                      : Promise.reject(new Error("外部端口不能使用 22、80、443"))
                  ),
                }]}
              >
                <InputNumber min={0} max={65535} precision={0} placeholder="不填则由上游分配" style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item name="int_port" label="内部端口" rules={[{ required: true, message: "请输入内部端口" }]}>
                <InputNumber min={0} max={65535} precision={0} style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item name="protocol" label="协议" rules={[{ required: true, message: "请选择协议" }]}>
                <Select
                  options={[
                    { value: 1, label: "TCP" },
                    { value: 2, label: "UDP" },
                    { value: 3, label: "TCP+UDP" },
                  ]}
                />
              </Form.Item>
            </Form>
          </Modal>
        </Space>
      ),
    }] : []),
    {
      key: "base",
      label: "基础信息",
      children: (
        <Row gutter={[16, 16]}>
          <Col xs={24} lg={14}>
            <Card variant="outlined" title="实例信息">
              <Descriptions column={2} bordered size="small">
                <Descriptions.Item label="实例 ID">#{instance.id}</Descriptions.Item>
                <Descriptions.Item label="状态">{tag(STATUS_META, instance.status)}</Descriptions.Item>
                <Descriptions.Item label="主机名">{instance.hostname || "-"}</Descriptions.Item>
                <Descriptions.Item label="别名">{instance.alias || "-"}</Descriptions.Item>
                <Descriptions.Item label="公网 IP">{instance.main_ip || <Tag>NAT网络</Tag>}</Descriptions.Item>
                <Descriptions.Item label="SSH 端口">{instance.ssh_port || "-"}</Descriptions.Item>
                <Descriptions.Item label="连接地址">{connectionAddress || "-"}</Descriptions.Item>
                <Descriptions.Item label="NAT 转发额度">{instance.nat_acl_limit ?? "-"}</Descriptions.Item>
                <Descriptions.Item label="产品">{instance.product_name}</Descriptions.Item>
                <Descriptions.Item label="产品组">{instance.product_group_name || "-"}</Descriptions.Item>
                <Descriptions.Item label="创建时间">{fmtDate(instance.created_at)}</Descriptions.Item>
                <Descriptions.Item label="销毁时间">{fmtDate(instance.terminated_at)}</Descriptions.Item>
              </Descriptions>
            </Card>
          </Col>
          <Col xs={24} lg={10}>
            <Card variant="outlined" title="用户信息">
              <Descriptions column={1} bordered size="small">
                <Descriptions.Item label="用户">{userLabel(instance)}</Descriptions.Item>
                <Descriptions.Item label="用户 ID">#{instance.user.id}</Descriptions.Item>
                <Descriptions.Item label="邮箱">{instance.user.email || "-"}</Descriptions.Item>
                <Descriptions.Item label="手机">{instance.user.phone || "-"}</Descriptions.Item>
                <Descriptions.Item label="余额">{yuan(instance.user.balance)}</Descriptions.Item>
              </Descriptions>
              <Button style={{ marginTop: 12 }} onClick={() => navigate(`/admin/users/${instance.user.id}`)}>
                查看用户详情
              </Button>
            </Card>
          </Col>
        </Row>
      ),
    },
  ]

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row gutter={[16, 16]} align="bottom" justify="space-between">
        <Col>
          <Button type="link" icon={<ArrowLeftOutlined />} style={{ paddingLeft: 0 }} onClick={() => navigate(backPath)}>
            {routeUserId ? "返回用户详情" : "返回实例管理"}
          </Button>
          <Space align="center" size={12}>
            <CloudServerOutlined style={{ fontSize: 34, color: "#1677ff" }} />
            <Space orientation="vertical" size={2}>
              <Title level={3} style={{ margin: 0 }}>
                {instance.hostname || instance.alias || `实例 #${instance.id}`}
              </Title>
              <Space wrap>
                {tag(STATUS_META, instance.status)}
                <Text type="secondary">用户 {userLabel(instance)}</Text>
                <Text type="secondary">产品 {instance.product_name}</Text>
              </Space>
            </Space>
          </Space>
        </Col>
        <Col>
          <Space wrap>
            <Button type="primary" icon={<ExportOutlined />} disabled={!instance.upstream_console_url} onClick={openUpstreamConsole}>
              服务器管理
            </Button>
            <Button icon={<ReloadOutlined />} onClick={() => void refreshAll()}>
              刷新
            </Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="下次续费" value={yuan(instance.next_renew_amount)} prefix={<WalletOutlined />} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="账户余额" value={yuan(instance.user.balance)} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="上游实例 ID" value={instance.upstream_id || "-"} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="到期时间" value={fmtDate(instance.expires_at)} /></Card>
        </Col>
      </Row>

      <Tabs items={tabs} />
    </Space>
  )
}
