import { useCallback, useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import {
  Alert,
  Badge,
  Button,
  Card,
  Col,
  Descriptions,
  Empty,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Spin,
  Statistic,
  Table,
  Tabs,
  Tag,
  Typography,
  message,
} from "antd"
import type { TableColumnsType } from "antd"
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  CrownOutlined,
  EyeOutlined,
  LockOutlined,
  ReloadOutlined,
  SyncOutlined,
  TeamOutlined,
} from "@ant-design/icons"
import {
  evaluateAgent,
  getAgentDetail,
  listAgents,
  listAgentTiers,
  manualAgentAction,
  reviewAgent,
  type AdminAgentItem,
  type AdminAgentTier,
  type AgentEvaluationLog,
  type AgentRiskEvent,
  type AgentStatusLog,
  type AgentTicketInfo,
} from "../api/agent"
import { formatYuan } from "../../utils/format"
import RichTextContent from "../../components/RichTextContent"

const { Text, Title, Paragraph } = Typography
const { TextArea } = Input

type BadgeStatus = "success" | "processing" | "warning" | "error" | "default"

const STATUS_MAP: Record<string, { label: string; color: BadgeStatus }> = {
  pending: { label: "待审核", color: "processing" },
  active: { label: "正常代理", color: "success" },
  observing: { label: "观察期", color: "warning" },
  risk_locked: { label: "风控锁定", color: "error" },
  suspended: { label: "已暂停", color: "warning" },
  rejected: { label: "已拒绝", color: "error" },
  terminated: { label: "已终止", color: "default" },
}

const ACTION_OPTIONS = [
  { label: "恢复代理", value: "restore" },
  { label: "进入观察期", value: "observe" },
  { label: "风控锁定", value: "risk_lock" },
  { label: "暂停并退回会员", value: "suspend" },
  { label: "终止代理", value: "terminate" },
]

const APPROVE_TEMPLATES = [
  "代理申请已通过，请在代理中心查看推广链接和结算规则。",
  "审核通过。请按平台推广规范开展推广，避免虚假宣传和恶意抢客。",
]

const REJECT_TEMPLATES = [
  "暂不符合代理申请条件，建议完善推广渠道和历史消费记录后再次申请。",
  "申请资料不完整，请补充推广渠道、客户来源和推广计划后再提交。",
]

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

function fmtRateBps(value?: number | null) {
  return `${((value ?? 0) / 100).toFixed(2)}%`
}

function statusBadge(status?: string | null) {
  if (!status) return <Badge status="default" text="-" />
  const meta = STATUS_MAP[status] || { label: status, color: "default" as BadgeStatus }
  return <Badge status={meta.color} text={meta.label} />
}

function actionLabel(action?: string | null) {
  const map: Record<string, string> = {
    none: "无变化",
    observe: "进入观察期",
    restore_active: "恢复正常",
    downgrade: "自动降档",
    return_member: "退回会员",
    risk_locked: "风控锁定",
    not_pass_manual_only: "未达标待人工处理",
    restore: "人工恢复",
    risk_lock: "人工风控锁定",
    suspend: "人工暂停",
    terminate: "人工终止",
  }
  return action ? (map[action] || action) : "-"
}

export default function AdminAgents() {
  const [loading, setLoading] = useState(true)
  const [items, setItems] = useState<AdminAgentItem[]>([])
  const [total, setTotal] = useState(0)
  const [keyword, setKeyword] = useState("")
  const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined)
  const [tiers, setTiers] = useState<AdminAgentTier[]>([])

  const [detailOpen, setDetailOpen] = useState(false)
  const [detailLoading, setDetailLoading] = useState(false)
  const [detail, setDetail] = useState<AdminAgentItem | null>(null)
  const [tickets, setTickets] = useState<AgentTicketInfo[]>([])
  const [evaluationLogs, setEvaluationLogs] = useState<AgentEvaluationLog[]>([])
  const [statusLogs, setStatusLogs] = useState<AgentStatusLog[]>([])
  const [riskEvents, setRiskEvents] = useState<AgentRiskEvent[]>([])

  const [reviewing, setReviewing] = useState(false)
  const [reviewAction, setReviewAction] = useState<"approve" | "reject" | null>(null)
  const [reviewRemark, setReviewRemark] = useState("")
  const [selectedTierId, setSelectedTierId] = useState<number | undefined>(undefined)

  const [actionOpen, setActionOpen] = useState(false)
  const [actionSaving, setActionSaving] = useState(false)
  const [actionForm] = Form.useForm<{ action: string; reason: string; agent_tier_id?: number }>()

  const reload = useCallback(async () => {
    setLoading(true)
    try {
      const [agentRes, tierRes] = await Promise.all([
        listAgents({ keyword: keyword || undefined, filter_status: filterStatus, limit: 50 }),
        listAgentTiers(),
      ])
      setItems(agentRes.data?.items ?? [])
      setTotal(agentRes.data?.total ?? 0)
      setTiers(tierRes.data ?? [])
    } catch {
      message.error("加载失败")
    } finally {
      setLoading(false)
    }
  }, [keyword, filterStatus])

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

  const enabledTiers = useMemo(() => tiers.filter((tier) => tier.enabled), [tiers])

  const openDetail = async (item: AdminAgentItem) => {
    setDetailOpen(true)
    setDetail(item)
    setSelectedTierId(item.agent_tier_id ?? undefined)
    setReviewAction(null)
    setReviewRemark("")
    setTickets([])
    setEvaluationLogs([])
    setStatusLogs([])
    setRiskEvents([])
    setDetailLoading(true)
    try {
      const res = await getAgentDetail(item.id)
      if (res.data) {
        setDetail(res.data)
        setSelectedTierId(res.data.agent_tier_id ?? undefined)
        setTickets(res.data.tickets ?? [])
        setEvaluationLogs(res.data.evaluation_logs ?? [])
        setStatusLogs(res.data.status_logs ?? [])
        setRiskEvents(res.data.risk_events ?? [])
      }
    } catch {
      message.error("加载代理详情失败")
    } finally {
      setDetailLoading(false)
    }
  }

  const closeDetail = () => {
    setDetailOpen(false)
    setDetail(null)
    setReviewAction(null)
    setReviewRemark("")
    setSelectedTierId(undefined)
  }

  const refreshCurrentDetail = async () => {
    if (!detail) return
    await openDetail(detail)
  }

  const handleReview = async (action: "approve" | "reject") => {
    if (!detail) return
    if (action === "approve" && !selectedTierId) {
      message.error("请选择代理档位")
      return
    }
    if (!reviewRemark.trim()) {
      message.error("请填写审核备注")
      return
    }
    setReviewing(true)
    setReviewAction(action)
    try {
      await reviewAgent(detail.id, {
        action,
        agent_tier_id: selectedTierId,
        reject_reason: action === "reject" ? reviewRemark.trim() : undefined,
        remark: reviewRemark.trim(),
      })
      message.success(action === "approve" ? "已通过审核" : "已拒绝申请")
      closeDetail()
      void reload()
    } catch (e: unknown) {
      const msg = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(msg || "操作失败")
    } finally {
      setReviewing(false)
    }
  }

  const handleEvaluate = async (item: AdminAgentItem) => {
    try {
      const res = await evaluateAgent(item.id)
      const action = String(res.data?.evaluation?.action || "none")
      message.success(`评估完成：${actionLabel(action)}`)
      await reload()
      if (detail?.id === item.id) {
        await openDetail(item)
      }
    } catch (e: unknown) {
      const msg = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(msg || "评估失败")
    }
  }

  const openManualAction = () => {
    if (!detail) return
    actionForm.setFieldsValue({
      action: "restore",
      reason: "",
      agent_tier_id: detail.agent_tier_id ?? undefined,
    })
    setActionOpen(true)
  }

  const submitManualAction = async () => {
    if (!detail) return
    try {
      const values = await actionForm.validateFields()
      setActionSaving(true)
      await manualAgentAction(detail.id, {
        action: values.action,
        reason: values.reason.trim(),
        agent_tier_id: values.agent_tier_id,
      })
      message.success("人工调整已保存")
      setActionOpen(false)
      await reload()
      await openDetail(detail)
    } catch (e: unknown) {
      if (e && typeof e === "object" && "errorFields" in e) return
      const msg = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(msg || "保存失败")
    } finally {
      setActionSaving(false)
    }
  }

  const columns: TableColumnsType<AdminAgentItem> = [
    {
      title: "代理用户",
      key: "user",
      width: 220,
      render: (_value, row) => row.user ? (
        <Space>
          <CrownOutlined style={{ fontSize: 16, color: "#1677ff" }} />
          <Space orientation="vertical" size={0}>
            <Link to={`/admin/users/${row.user_id}`}>
              <Text strong>{row.user.nickname || row.user.username}</Text>
            </Link>
            <Text type="secondary" style={{ fontSize: 12 }}>ID {row.user_id} · {row.user.email || "-"}</Text>
          </Space>
        </Space>
      ) : <Text type="secondary">用户 #{row.user_id}</Text>,
    },
    { title: "状态", dataIndex: "status", width: 110, render: statusBadge },
    {
      title: "代理档位",
      key: "tier",
      width: 130,
      render: (_value, row) => row.agent_tier ? <Tag color="blue">{row.agent_tier.name}</Tag> : <Tag>未分配</Tag>,
    },
    {
      title: "邀请码",
      dataIndex: "invite_code",
      width: 140,
      render: (value: string | null) => value ? <Text copyable style={{ fontSize: 12 }}>{value}</Text> : "-",
    },
    { title: "累计销售", dataIndex: "total_sales", width: 110, align: "right", render: formatYuan },
    { title: "代理收益", dataIndex: "total_profit", width: 110, align: "right", render: formatYuan },
    { title: "最后评估", dataIndex: "last_evaluated_at", width: 170, render: fmtTime },
    {
      title: "操作",
      key: "action",
      width: 210,
      align: "right",
      render: (_value, row) => (
        <Space size={4}>
          <Button size="small" icon={<EyeOutlined />} onClick={() => openDetail(row)}>详情</Button>
          {["active", "observing"].includes(row.status) && (
            <Button size="small" icon={<SyncOutlined />} onClick={() => handleEvaluate(row)}>评估</Button>
          )}
        </Space>
      ),
    },
  ]

  const stats = useMemo(() => ({
    total: items.length,
    pending: items.filter((item) => item.status === "pending").length,
    active: items.filter((item) => item.status === "active").length,
    observing: items.filter((item) => item.status === "observing").length,
    riskLocked: items.filter((item) => item.status === "risk_locked").length,
  }), [items])

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row justify="space-between" align="bottom">
        <Col>
          <Title level={3}>代理管理</Title>
          <Paragraph type="secondary">审核代理申请，查看 30 天考核结果，并处理自动升降级和风控状态。</Paragraph>
        </Col>
        <Col>
          <Button icon={<ReloadOutlined />} loading={loading} onClick={reload}>刷新</Button>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={6}><Card variant="outlined"><Statistic title="代理记录" value={stats.total} prefix={<TeamOutlined />} /></Card></Col>
        <Col xs={24} sm={6}><Card variant="outlined"><Statistic title="待审核" value={stats.pending} prefix={<CheckCircleOutlined />} styles={{ content: { color: stats.pending > 0 ? "#faad14" : undefined } }} /></Card></Col>
        <Col xs={24} sm={6}><Card variant="outlined"><Statistic title="观察期" value={stats.observing} prefix={<SyncOutlined />} styles={{ content: { color: stats.observing > 0 ? "#faad14" : undefined } }} /></Card></Col>
        <Col xs={24} sm={6}><Card variant="outlined"><Statistic title="风控锁定" value={stats.riskLocked} prefix={<LockOutlined />} styles={{ content: { color: stats.riskLocked > 0 ? "#ff4d4f" : undefined } }} /></Card></Col>
      </Row>

      <Card
        variant="outlined"
        title={
          <Space wrap>
            <Input.Search placeholder="搜索用户名或邮箱" allowClear onSearch={(value) => setKeyword(value)} style={{ width: 240 }} />
            <Select
              placeholder="状态筛选"
              allowClear
              style={{ width: 150 }}
              value={filterStatus}
              onChange={(value) => setFilterStatus(value)}
              options={Object.entries(STATUS_MAP).map(([value, meta]) => ({ value, label: meta.label }))}
            />
          </Space>
        }
      >
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={items}
          pagination={{ pageSize: 20, showSizeChanger: false, total }}
          size="middle"
          scroll={{ x: 1180 }}
          locale={{ emptyText: <Empty description="暂无代理记录" /> }}
        />
      </Card>

      <Modal
        title={detail?.status === "pending" ? "审核代理申请" : "代理详情"}
        open={detailOpen}
        onCancel={closeDetail}
        footer={null}
        width={860}
        destroyOnHidden
      >
        {detail && (
          <Spin spinning={detailLoading}>
            <Space orientation="vertical" size="middle" style={{ width: "100%" }}>
              <Card size="small" title="基础信息">
                <Descriptions column={2} size="small">
                  <Descriptions.Item label="用户">
                    <Link to={`/admin/users/${detail.user_id}`}>{detail.user?.nickname || detail.user?.username || `#${detail.user_id}`}</Link>
                  </Descriptions.Item>
                  <Descriptions.Item label="状态">{statusBadge(detail.status)}</Descriptions.Item>
                  <Descriptions.Item label="邮箱">{detail.user?.email || "-"}</Descriptions.Item>
                  <Descriptions.Item label="手机">{detail.user?.phone || "-"}</Descriptions.Item>
                  <Descriptions.Item label="当前档位">{detail.agent_tier?.name || "-"}</Descriptions.Item>
                  <Descriptions.Item label="邀请码">{detail.invite_code ? <Text copyable>{detail.invite_code}</Text> : "-"}</Descriptions.Item>
                  <Descriptions.Item label="观察开始">{fmtTime(detail.observe_started_at)}</Descriptions.Item>
                  <Descriptions.Item label="观察截止">{fmtTime(detail.observe_until)}</Descriptions.Item>
                  <Descriptions.Item label="风控时间">{fmtTime(detail.risk_locked_at)}</Descriptions.Item>
                  <Descriptions.Item label="最后评估">{fmtTime(detail.last_evaluated_at)}</Descriptions.Item>
                  <Descriptions.Item label="风控原因" span={2}>{detail.risk_reason || "-"}</Descriptions.Item>
                </Descriptions>
              </Card>

              {detail.status === "risk_locked" && (
                <Alert type="error" showIcon title="该代理已被风控锁定" description="锁定期间不会产生新的代理差价结算，需要人工确认后恢复或暂停。" />
              )}
              {detail.status === "observing" && (
                <Alert type="warning" showIcon title="该代理处于观察期" description="观察期内仍按当前代理档位结算，到期后若仍不达标会自动降档或退回会员。" />
              )}

              <Tabs
                items={[
                  {
                    key: "review",
                    label: "申请/审核",
                    children: (
                      <Space orientation="vertical" size="middle" style={{ width: "100%" }}>
                        {(detail.apply_tier || detail.apply_reason || detail.apply_channels) && (
                          <Card size="small" title="申请信息">
                            <Descriptions column={1} size="small">
                              <Descriptions.Item label="申请档位">{detail.apply_tier || "-"}</Descriptions.Item>
                              <Descriptions.Item label="申请理由">{detail.apply_reason || "-"}</Descriptions.Item>
                              <Descriptions.Item label="推广渠道">{detail.apply_channels || "-"}</Descriptions.Item>
                            </Descriptions>
                          </Card>
                        )}
                        {detail.review_message && <Alert type="info" showIcon title="审核备注" description={detail.review_message} />}
                        {detail.status === "pending" && (
                          <Card size="small" title="审核处理">
                            <Space orientation="vertical" size="middle" style={{ width: "100%" }}>
                              <Select
                                placeholder="选择代理档位"
                                style={{ width: "100%" }}
                                value={selectedTierId}
                                onChange={setSelectedTierId}
                                options={enabledTiers.map((tier) => ({ label: `${tier.name} (${fmtRateBps(tier.cost_rate)})`, value: tier.id }))}
                              />
                              <Space wrap>
                                <Text type="secondary">快捷备注</Text>
                                {reviewAction === "approve" && APPROVE_TEMPLATES.map((text, index) => (
                                  <Button key={text} size="small" onClick={() => setReviewRemark(text)}>模板 {index + 1}</Button>
                                ))}
                                {reviewAction === "reject" && REJECT_TEMPLATES.map((text, index) => (
                                  <Button key={text} size="small" onClick={() => setReviewRemark(text)}>模板 {index + 1}</Button>
                                ))}
                              </Space>
                              <TextArea rows={4} value={reviewRemark} onChange={(event) => setReviewRemark(event.target.value)} placeholder="填写审核备注，用户可见" maxLength={500} showCount />
                              <Row gutter={12}>
                                <Col span={12}>
                                  <Button block type="primary" icon={<CheckCircleOutlined />} loading={reviewing && reviewAction === "approve"} onClick={() => handleReview("approve")}>通过</Button>
                                </Col>
                                <Col span={12}>
                                  <Button block danger icon={<CloseCircleOutlined />} loading={reviewing && reviewAction === "reject"} onClick={() => handleReview("reject")}>拒绝</Button>
                                </Col>
                              </Row>
                            </Space>
                          </Card>
                        )}
                        {tickets.length > 0 && (
                          <Card size="small" title="关联工单">
                            <Space orientation="vertical" style={{ width: "100%" }}>
                              {tickets.map((ticket) => (
                                <Card key={ticket.ticket_id} size="small" title={<Space><Link to={`/admin/tickets/${ticket.ticket_id}`}>{ticket.ticket_no}</Link><Text>{ticket.subject}</Text><Tag>{ticket.status}</Tag></Space>}>
                                  <Space orientation="vertical" style={{ width: "100%" }}>
                                    {ticket.messages.map((item) => (
                                      <div key={item.id} style={{ padding: 8, background: "#fafafa", borderRadius: 6 }}>
                                        <Space>
                                          <Tag>{item.sender_type}</Tag>
                                          <Text type="secondary" style={{ fontSize: 12 }}>{fmtTime(item.created_at)}</Text>
                                        </Space>
                                        <div style={{ marginTop: 4, wordBreak: "break-word" }}>
                                          <RichTextContent value={item.content} admin />
                                        </div>
                                      </div>
                                    ))}
                                  </Space>
                                </Card>
                              ))}
                            </Space>
                          </Card>
                        )}
                      </Space>
                    ),
                  },
                  {
                    key: "lifecycle",
                    label: "考核/风控",
                    children: (
                      <Space orientation="vertical" size="middle" style={{ width: "100%" }}>
                        <Row gutter={12}>
                          <Col>
                            <Button icon={<SyncOutlined />} disabled={!["active", "observing"].includes(detail.status)} onClick={() => handleEvaluate(detail)}>立即评估</Button>
                          </Col>
                          <Col>
                            <Button icon={<LockOutlined />} onClick={openManualAction}>人工调整</Button>
                          </Col>
                          <Col>
                            <Button icon={<ReloadOutlined />} onClick={refreshCurrentDetail}>刷新详情</Button>
                          </Col>
                        </Row>
                        <Card size="small" title="最近一次考核快照">
                          <SnapshotView snapshot={detail.last_evaluation_snapshot} />
                        </Card>
                        <Card size="small" title="评估日志">
                          <Table
                            rowKey="id"
                            size="small"
                            pagination={false}
                            dataSource={evaluationLogs}
                            columns={evaluationColumns()}
                            scroll={{ x: 980 }}
                            locale={{ emptyText: <Empty description="暂无评估日志" /> }}
                          />
                        </Card>
                        <Card size="small" title="状态日志">
                          <Table
                            rowKey="id"
                            size="small"
                            pagination={false}
                            dataSource={statusLogs}
                            columns={statusLogColumns()}
                            scroll={{ x: 880 }}
                            locale={{ emptyText: <Empty description="暂无状态日志" /> }}
                          />
                        </Card>
                        <Card size="small" title="风控事件">
                          <Table
                            rowKey="id"
                            size="small"
                            pagination={false}
                            dataSource={riskEvents}
                            columns={riskEventColumns()}
                            scroll={{ x: 720 }}
                            locale={{ emptyText: <Empty description="暂无风控事件" /> }}
                          />
                        </Card>
                      </Space>
                    ),
                  },
                ]}
              />
            </Space>
          </Spin>
        )}
      </Modal>

      <Modal
        title="人工调整代理状态"
        open={actionOpen}
        onCancel={() => setActionOpen(false)}
        onOk={submitManualAction}
        confirmLoading={actionSaving}
        destroyOnHidden
      >
        <Alert
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
          title="人工调整会写入状态日志"
          description="请写明原因，方便后续复盘自动降级、风控锁定或恢复代理的依据。"
        />
        <Form form={actionForm} layout="vertical">
          <Form.Item name="action" label="操作" rules={[{ required: true, message: "请选择操作" }]}>
            <Select options={ACTION_OPTIONS} />
          </Form.Item>
          <Form.Item name="agent_tier_id" label="代理档位">
            <Select allowClear placeholder="恢复或观察时可选择档位" options={enabledTiers.map((tier) => ({ label: tier.name, value: tier.id }))} />
          </Form.Item>
          <Form.Item name="reason" label="原因" rules={[{ required: true, message: "请写明调整原因" }]}>
            <TextArea rows={4} maxLength={500} showCount placeholder="例如：已补充渠道证明，人工恢复代理；或风控复核后暂停代理。" />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  )
}

function SnapshotView({ snapshot }: { snapshot: Record<string, unknown> | null }) {
  if (!snapshot) return <Empty description="暂无快照" />
  const tier = (snapshot.tier || {}) as Record<string, unknown>
  return (
    <Descriptions column={2} size="small">
      <Descriptions.Item label="周期开始">{String(snapshot.period_start || "-")}</Descriptions.Item>
      <Descriptions.Item label="周期结束">{String(snapshot.period_end || "-")}</Descriptions.Item>
      <Descriptions.Item label="净销售额">{formatYuan(Number(snapshot.net_sales || 0))}</Descriptions.Item>
      <Descriptions.Item label="毛销售额">{formatYuan(Number(snapshot.gross_sales || 0))}</Descriptions.Item>
      <Descriptions.Item label="退款金额">{formatYuan(Number(snapshot.refund_amount || 0))}</Descriptions.Item>
      <Descriptions.Item label="退款率">{fmtRateBps(Number(snapshot.refund_rate_bps || 0))}</Descriptions.Item>
      <Descriptions.Item label="有效客户数">{String(snapshot.active_customers ?? 0)}</Descriptions.Item>
      <Descriptions.Item label="补贴亏损">{formatYuan(Number(snapshot.subsidy_loss || 0))}</Descriptions.Item>
      <Descriptions.Item label="要求净销售额">{formatYuan(Number(tier.monthly_sales_required || 0))}</Descriptions.Item>
      <Descriptions.Item label="要求有效客户">{String(tier.monthly_active_customers_required ?? 0)}</Descriptions.Item>
    </Descriptions>
  )
}

function evaluationColumns(): TableColumnsType<AgentEvaluationLog> {
  return [
    { title: "时间", dataIndex: "created_at", width: 170, render: fmtTime },
    { title: "动作", dataIndex: "action", width: 130, render: actionLabel },
    { title: "是否达标", dataIndex: "passed", width: 90, render: (value: boolean) => value ? <Tag color="green">达标</Tag> : <Tag color="gold">未达标</Tag> },
    { title: "净销售额", dataIndex: "net_sales", width: 110, align: "right", render: formatYuan },
    { title: "有效客户", dataIndex: "active_customers", width: 90, align: "center" },
    { title: "退款率", dataIndex: "refund_rate_bps", width: 90, align: "right", render: fmtRateBps },
    { title: "补贴亏损", dataIndex: "subsidy_loss", width: 110, align: "right", render: formatYuan },
    { title: "原因", dataIndex: "reason", width: 260, ellipsis: true },
  ]
}

function statusLogColumns(): TableColumnsType<AgentStatusLog> {
  return [
    { title: "时间", dataIndex: "created_at", width: 170, render: fmtTime },
    { title: "来源", dataIndex: "source", width: 90, render: (value: string) => <Tag>{value}</Tag> },
    { title: "动作", dataIndex: "action", width: 130, render: actionLabel },
    { title: "变更前", dataIndex: "before_status", width: 110, render: statusBadge },
    { title: "变更后", dataIndex: "after_status", width: 110, render: statusBadge },
    { title: "原因", dataIndex: "reason", width: 300, ellipsis: true },
  ]
}

function riskEventColumns(): TableColumnsType<AgentRiskEvent> {
  return [
    { title: "时间", dataIndex: "created_at", width: 170, render: fmtTime },
    { title: "类型", dataIndex: "event_type", width: 150 },
    { title: "等级", dataIndex: "severity", width: 90, render: (value: string) => <Tag color={value === "critical" ? "red" : "orange"}>{value}</Tag> },
    { title: "状态", dataIndex: "status", width: 90, render: (value: string) => <Tag>{value}</Tag> },
    { title: "原因", dataIndex: "reason", width: 300, ellipsis: true },
  ]
}
