import { useEffect, useMemo, useState, type ReactNode } from "react"
import { Link, useNavigate } from "react-router-dom"
import {
  CloudServerOutlined,
  CopyOutlined,
  DatabaseOutlined,
  DesktopOutlined,
  EyeOutlined,
  GlobalOutlined,
  LinkOutlined,
  PlusOutlined,
  ReloadOutlined,
} from "@ant-design/icons"
import { Button, Card, Col, Empty, Row, Space, Spin, Table, Tag, Tooltip, Typography } from "antd"
import { toast } from "../utils/toast"
import { osLogo } from "../utils/osLogo"
import { listServers, type ServerItem } from "../api/servers"
import { isPluginServer } from "./server-detail/helpers"

const { Title, Text, Paragraph } = Typography

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

const NORMAL_SERVER_STATUSES = new Set(["active", "provisioning", "suspended"])

function copyText(text: string, label: string) {
  navigator.clipboard.writeText(text).then(() => toast.success(`已复制${label}`))
}

function formatMemory(mb: number | null) {
  if (!mb) return "-"
  return mb >= 1024 ? `${(mb / 1024).toFixed(mb % 1024 === 0 ? 0 : 1)} GB` : `${mb} MB`
}

function formatDate(value: string | null) {
  if (!value) return "-"
  return new Date(value).toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  })
}

function emptyIpNetworkLabel(record: ServerItem) {
  const values = [record.nat_acl_limit, record.nat_web_limit]
    .filter((value): value is number => typeof value === "number")

  if (values.some((value) => value >= 0)) return "NAT网络"
  if (values.length > 0 && values.every((value) => value === -1)) return "无网络"
  return "-"
}

function resolveDisplayStatus(status: string, upstreamPower?: string | null) {
  if (status && status !== "active") {
    return { key: status, ...(SERVER_STATUS[status] ?? { label: status || "未知", color: "default" }) }
  }

  if (upstreamPower) {
    const normalized = upstreamPower.toLowerCase()
    const isOff = normalized === "off" || normalized.includes("off") || upstreamPower.includes("关")
    const isOn = normalized === "on" || upstreamPower.includes("开") || upstreamPower.includes("运行")

    if (isOff) return { key: "off", label: "已关机", color: "default" }
    if (isOn) return { key: "active", label: "运行中", color: "success" }
    return { key: "power", label: upstreamPower, color: "processing" }
  }

  return { key: status, ...(SERVER_STATUS[status] ?? { label: status || "未知", color: "default" }) }
}

function statusTag(record: ServerItem) {
  const meta = resolveDisplayStatus(record.status, record.upstream_power)
  return <Tag color={meta.color}>{meta.label}</Tag>
}

export default function ServerList() {
  const navigate = useNavigate()
  const [servers, setServers] = useState<ServerItem[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  const load = async (mode: "initial" | "manual" | "auto" = "initial") => {
    if (mode === "manual") setRefreshing(true)
    if (mode === "initial") setLoading(true)

    try {
      const res = await listServers()
      const list = res.data.data ?? []
      setServers(list)
      const normalCount = list.filter((s) => NORMAL_SERVER_STATUSES.has(s.status)).length
      if (mode === "manual") toast.success(`已刷新，共 ${normalCount} 台`)
    } catch {
      toast.error("服务器列表加载失败")
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }

  useEffect(() => { load() }, [])

  const visible = useMemo(
    () => servers.filter((s) => NORMAL_SERVER_STATUSES.has(s.status)),
    [servers],
  )

  const provisioningCount = useMemo(
    () => visible.filter((s) => s.status === "provisioning").length,
    [visible],
  )

  const activeCount = useMemo(
    () => visible.filter((s) => resolveDisplayStatus(s.status, s.upstream_power).key === "active").length,
    [visible],
  )

  useEffect(() => {
    if (provisioningCount === 0) return
    const timer = setInterval(() => load("auto"), 5000)
    return () => clearInterval(timer)
  }, [provisioningCount])

  if (loading) {
    return (
      <div style={{ height: 420, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Spin size="large" description="正在加载服务器" />
      </div>
    )
  }

  return (
    <Space orientation="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 }}>
            查看云服务器实例、运行状态、主 IP 和到期时间。
          </Paragraph>
        </Col>
        <Col>
          <Space wrap>
            <Button icon={<ReloadOutlined />} loading={refreshing} onClick={() => load("manual")}>
              刷新
            </Button>
            <Link to="/store">
              <Button type="primary" icon={<PlusOutlined />}>购买服务器</Button>
            </Link>
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} md={8}>
          <Card variant="outlined">
            <MetricCard
              label="全部实例"
              value={visible.length}
              suffix="台"
              icon={<CloudServerOutlined />}
              bg="#e6f4ff"
              color="#1677ff"
            />
          </Card>
        </Col>
        <Col xs={24} md={8}>
          <Card variant="outlined">
            <MetricCard
              label="运行中"
              value={activeCount}
              suffix="台"
              icon={<DesktopOutlined />}
              bg="#f6ffed"
              color="#52c41a"
            />
          </Card>
        </Col>
        <Col xs={24} md={8}>
          <Card variant="outlined">
            <MetricCard
              label="开通中"
              value={provisioningCount}
              suffix="台"
              icon={<ReloadOutlined />}
              bg="#fff7e6"
              color="#fa8c16"
            />
          </Card>
        </Col>
      </Row>

      <Card variant="outlined" title={<Space><CloudServerOutlined /> 实例列表</Space>}>
        {visible.length === 0 ? (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="暂无服务器实例"
          >
            <Link to="/store">
              <Button type="primary" icon={<PlusOutlined />}>立即购买</Button>
            </Link>
          </Empty>
        ) : (
          <Table
            rowKey="id"
            dataSource={visible}
            pagination={{ pageSize: 10, showSizeChanger: false }}
            scroll={{ x: 980 }}
            onRow={(record) => ({
              onClick: () => navigate(`/control/server/${record.id}`),
              style: { cursor: "pointer" },
            })}
            columns={[
              {
                title: "实例",
                dataIndex: "hostname",
                width: 260,
                render: (_: unknown, record: ServerItem) => {
                  const isPlugin = isPluginServer(record)
                  return (
                    <Space size={12}>
                      <div
                        style={{
                          width: 38,
                          height: 38,
                          borderRadius: 8,
                          border: "1px solid #f0f0f0",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          background: isPlugin ? "#f0f5ff" : "#fafafa",
                        }}
                      >
                        {isPlugin ? (
                          <LinkOutlined style={{ fontSize: 18, color: "#1677ff" }} />
                        ) : (
                          <img src={osLogo(record.os_image)} alt="" style={{ width: 24, height: 24, objectFit: "contain" }} />
                        )}
                      </div>
                      <div style={{ minWidth: 0 }}>
                        <Text strong>{record.hostname || `实例 #${record.id}`}</Text>
                        <div>
                          <Text type="secondary" style={{ fontSize: 12 }}>
                            {record.product_name}
                            {isPlugin && <Tag color="blue" style={{ marginLeft: 6, fontSize: 10 }}>插件</Tag>}
                          </Text>
                        </div>
                      </div>
                    </Space>
                  )
                },
              },
              {
                title: "状态",
                dataIndex: "status",
                width: 150,
                render: (_: unknown, record: ServerItem) => (
                  <Space size={4} wrap>
                    {statusTag(record)}
                  </Space>
                ),
              },
              {
                title: "配置",
                key: "config",
                width: 180,
                render: (_: unknown, record: ServerItem) => {
                  if (isPluginServer(record)) {
                    return <Text type="secondary">{record.provision_plugin?.name || "其他产品"}</Text>
                  }
                  return (
                    <Space orientation="vertical" size={2}>
                      <Text>
                        <DatabaseOutlined /> {record.cpu ?? "-"} 核 / {formatMemory(record.memory)}
                      </Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        系统盘 {record.system_disk_size ?? "-"} GB
                      </Text>
                    </Space>
                  )
                },
              },
              {
                title: "主 IP",
                dataIndex: "main_ip",
                width: 170,
                render: (value: string | null, record: ServerItem) => {
                  if (isPluginServer(record)) {
                    return (
                      <Text type="secondary">
                        {record.hostname ? <><LinkOutlined /> {record.hostname}</> : "—"}
                      </Text>
                    )
                  }
                  return (
                    value ? (
                      <Space onClick={(e) => e.stopPropagation()}>
                        <Text code>{value}</Text>
                        <Tooltip title="复制 IP">
                          <Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copyText(value, "IP")} />
                        </Tooltip>
                      </Space>
                    ) : (
                      <Text type="secondary">{emptyIpNetworkLabel(record)}</Text>
                    )
                  )
                },
              },
              {
                title: "网络",
                key: "network",
                width: 140,
                render: (_: unknown, record: ServerItem) => {
                  if (isPluginServer(record)) {
                    return <Text type="secondary">—</Text>
                  }
                  return (
                    <Text type="secondary">
                      <GlobalOutlined /> {record.out_bw ?? "-"} Mbps
                    </Text>
                  )
                },
              },
              {
                title: "到期时间",
                dataIndex: "expires_at",
                width: 140,
                render: (value: string | null) => <Text type="secondary">{formatDate(value)}</Text>,
              },
              {
                title: "操作",
                key: "action",
                align: "right" as const,
                width: 110,
                render: (_: unknown, record: ServerItem) => (
                  <Button
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={(e) => {
                      e.stopPropagation()
                      navigate(`/control/server/${record.id}`)
                    }}
                  >
                    详情
                  </Button>
                ),
              },
            ]}
          />
        )}
      </Card>
    </Space>
  )
}

function MetricCard({
  label,
  value,
  suffix,
  icon,
  bg,
  color,
}: {
  label: string
  value: number
  suffix: string
  icon: ReactNode
  bg: string
  color: string
}) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
      <div>
        <Text type="secondary">{label}</Text>
        <div style={{ marginTop: 8, display: "flex", alignItems: "baseline", gap: 4 }}>
          <span style={{ fontSize: 30, lineHeight: 1, fontWeight: 700, color: "#1f2937" }}>{value}</span>
          <span style={{ color: "#8c8c8c", fontSize: 14 }}>{suffix}</span>
        </div>
      </div>
      <div
        style={{
          width: 46,
          height: 46,
          borderRadius: 12,
          background: bg,
          color,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          fontSize: 22,
        }}
      >
        {icon}
      </div>
    </div>
  )
}
