import { useCallback, useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import {
  AuditOutlined,
  CloudServerOutlined,
  DatabaseOutlined,
  FolderOpenOutlined,
  ProductOutlined,
  ReloadOutlined,
  RightOutlined,
  SafetyCertificateOutlined,
  TeamOutlined,
  UserAddOutlined,
  WalletOutlined,
} from "@ant-design/icons"
import { Button, Card, Col, Empty, Progress, Row, Skeleton, Space, Statistic, Table, Tag, Typography, message, theme } from "antd"
import { useAdminAuth } from "../contexts/AdminAuthContext"
import { getAdminDashboard, type AdminDashboardData } from "../api/dashboard"

const { Title, Text, Paragraph } = Typography

const quickLinks = [
  { title: "用户管理", desc: "查看用户、状态和账户信息", icon: <TeamOutlined />, href: "/admin/users" },
  { title: "产品管理", desc: "维护商品、价格和配置", icon: <ProductOutlined />, href: "/admin/products" },
  { title: "分类与组", desc: "管理前台产品分类结构", icon: <FolderOpenOutlined />, href: "/admin/product-catalog" },
  { title: "财务管理", desc: "查看充值订单和资金流水", icon: <WalletOutlined />, href: "/admin/finance" },
  { title: "魔方云节点", desc: "维护上游云服务器接口", icon: <CloudServerOutlined />, href: "/admin/cloud-servers" },
]

const STATUS_META: Record<string, { label: string; color: string }> = {
  active: { label: "正常", color: "green" },
  inactive: { label: "未激活", color: "default" },
  banned: { label: "已封禁", color: "red" },
  paid: { label: "已支付", color: "green" },
  pending: { label: "待处理", color: "warning" },
  cancelled: { label: "已退订", color: "default" },
  refunded: { label: "已退款", color: "purple" },
  success: { label: "成功", color: "green" },
  failed: { label: "失败", color: "red" },
  running: { label: "执行中", color: "blue" },
  submitted: { label: "已下发", color: "processing" },
  no_task: { label: "已完成", color: "green" },
  manual_handled: { label: "人工已处理", color: "purple" },
  ignored: { label: "无需处理", color: "default" },
}

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

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

export default function AdminDashboard() {
  const { token } = theme.useToken()
  const { admin } = useAdminAuth()
  const [loading, setLoading] = useState(true)
  const [dashboard, setDashboard] = useState<AdminDashboardData | null>(null)

  const loadDashboard = useCallback(async () => {
    setLoading(true)
    try {
      const res = await getAdminDashboard()
      setDashboard(res.data ?? null)
    } catch {
      message.error("加载仪表盘数据失败")
    } finally {
      setLoading(false)
    }
  }, [])

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

  const displayName = admin?.nickname || admin?.username || "管理员"
  const stats = dashboard?.stats
  const overview = dashboard?.overview
  const statItems = useMemo(() => [
    {
      title: "用户总数",
      value: stats?.users_total ?? 0,
      suffix: "人",
      note: "平台注册用户",
      icon: <TeamOutlined />,
      color: "#1677ff",
    },
    {
      title: "今日收入",
      value: (stats?.today_income_cents ?? 0) / 100,
      prefix: "¥",
      precision: 2,
      note: "今日已到账充值",
      icon: <WalletOutlined />,
      color: "#52c41a",
    },
    {
      title: "产品数量",
      value: stats?.products_total ?? 0,
      suffix: "个",
      note: `在售 ${stats?.products_active ?? 0} 个`,
      icon: <ProductOutlined />,
      color: "#722ed1",
    },
    {
      title: "云节点",
      value: stats?.cloud_nodes_total ?? 0,
      suffix: "个",
      note: `在线 ${stats?.cloud_nodes_online ?? 0} / 启用 ${stats?.cloud_nodes_enabled ?? 0}`,
      icon: <CloudServerOutlined />,
      color: "#fa8c16",
    },
  ], [stats])

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

  return (
    <Space orientation="vertical" size={24} style={{ width: "100%" }}>
      <Card variant="outlined">
        <Row gutter={[24, 24]} align="middle" justify="space-between">
          <Col xs={24} lg={15}>
            <Space orientation="vertical" size={8}>
              <Tag color="blue" icon={<SafetyCertificateOutlined />}>Admin Dashboard</Tag>
              <Title level={2} style={{ margin: 0 }}>欢迎回来，{displayName}</Title>
              <Paragraph type="secondary" style={{ margin: 0, maxWidth: 680 }}>
                这里集中展示用户、财务、产品、订单和魔方云节点的实时运营数据。
              </Paragraph>
            </Space>
          </Col>
          <Col xs={24} lg="auto">
            <Space wrap>
              <Button icon={<ReloadOutlined />} loading={loading} onClick={() => void loadDashboard()}>刷新数据</Button>
              <Link to="/admin/products">
                <Button type="primary" icon={<ProductOutlined />}>管理产品</Button>
              </Link>
            </Space>
          </Col>
        </Row>
      </Card>

      <Row gutter={[16, 16]}>
        {statItems.map((item) => (
          <Col xs={24} sm={12} xl={6} key={item.title}>
            <Card variant="outlined">
              <Space align="start" style={{ width: "100%", justifyContent: "space-between" }}>
                <Statistic title={item.title} value={item.value} prefix={item.prefix} suffix={item.suffix} precision={item.precision} />
                <span style={{ color: item.color, fontSize: 24 }}>{item.icon}</span>
              </Space>
              <Text type="secondary" style={{ display: "block", marginTop: 12 }}>{item.note}</Text>
            </Card>
          </Col>
        ))}
      </Row>

      <Row gutter={[16, 16]} align="stretch">
        <Col xs={24} xl={16}>
          <Card
            variant="outlined"
            title={<Space><DatabaseOutlined /> 运营概览</Space>}
            extra={<Tag color="green">实时数据</Tag>}
          >
            <Space orientation="vertical" size={18} style={{ width: "100%" }}>
              <div>
                <Space style={{ width: "100%", justifyContent: "space-between" }}>
                  <Text>订单处理能力</Text>
                  <Text type="secondary">{overview?.order_processing_percent ?? 0}%</Text>
                </Space>
                <Progress percent={overview?.order_processing_percent ?? 0} showInfo={false} strokeColor={token.colorPrimary} />
                <Text type="secondary" style={{ fontSize: 12 }}>待处理订单 {overview?.pending_orders ?? 0} 笔</Text>
              </div>
              <div>
                <Space style={{ width: "100%", justifyContent: "space-between" }}>
                  <Text>云节点连通率</Text>
                  <Text type="secondary">{overview?.cloud_connectivity_percent ?? 0}%</Text>
                </Space>
                <Progress percent={overview?.cloud_connectivity_percent ?? 0} showInfo={false} strokeColor="#52c41a" />
                <Text type="secondary" style={{ fontSize: 12 }}>资源异常动作 {overview?.failed_resource_actions ?? 0} 条</Text>
              </div>
              <div>
                <Space style={{ width: "100%", justifyContent: "space-between" }}>
                  <Text>财务对账进度</Text>
                  <Text type="secondary">{overview?.finance_reconcile_percent ?? 0}%</Text>
                </Space>
                <Progress percent={overview?.finance_reconcile_percent ?? 0} showInfo={false} strokeColor="#faad14" />
                <Text type="secondary" style={{ fontSize: 12 }}>待支付充值 {overview?.pending_recharges ?? 0} 笔</Text>
              </div>
            </Space>
          </Card>
        </Col>

        <Col xs={24} xl={8}>
          <Card variant="outlined" title={<Space><AuditOutlined /> 快捷入口</Space>}>
            <Space orientation="vertical" size={0} style={{ width: "100%" }}>
              {quickLinks.map((item, index) => (
                <Link key={item.href} to={item.href} style={{ color: "inherit" }}>
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      gap: 12,
                      padding: "12px 0",
                      borderBottom: index === quickLinks.length - 1 ? undefined : `1px solid ${token.colorBorderSecondary}`,
                    }}
                  >
                    <Space size={12} align="start">
                      <span style={{ color: token.colorPrimary, fontSize: 20 }}>{item.icon}</span>
                      <Space orientation="vertical" size={2}>
                        <Text strong>{item.title}</Text>
                        <Text type="secondary" style={{ fontSize: 12 }}>{item.desc}</Text>
                      </Space>
                    </Space>
                    <RightOutlined style={{ color: token.colorTextTertiary }} />
                  </div>
                </Link>
              ))}
            </Space>
          </Card>
        </Col>
      </Row>

      <Card variant="outlined" title={<Space><UserAddOutlined /> 最近动态</Space>} extra={<Tag color="blue">实时数据</Tag>}>
        <Table
          rowKey="key"
          pagination={false}
          dataSource={dashboard?.recent_events ?? []}
          locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无动态" /> }}
          columns={[
            { title: "类型", dataIndex: "type", width: 120 },
            { title: "事件", dataIndex: "action" },
            { title: "状态", dataIndex: "status", width: 120, render: statusTag },
            { title: "时间", dataIndex: "time", width: 150, render: formatDate },
          ]}
        />
      </Card>
    </Space>
  )
}
