import { useCallback, useEffect, useMemo, useState } from "react"
import {
  ApiOutlined,
  CheckCircleOutlined,
  CloudServerOutlined,
  DeleteOutlined,
  EditOutlined,
  GlobalOutlined,
  PlusOutlined,
  ReloadOutlined,
  SafetyCertificateOutlined,
  ThunderboltOutlined,
  WarningOutlined,
} from "@ant-design/icons"
import {
  Avatar,
  Button,
  Card,
  Col,
  Empty,
  Popconfirm,
  Row,
  Space,
  Statistic,
  Table,
  Tag,
  Tooltip,
  Typography,
  theme,
  type TableColumnsType,
} from "antd"
import { PageSkeleton, type SkeletonSpec } from "../../utils/skeleton"
import { toast } from "../../utils/toast"
import CloudServerFormModal from "../components/CloudServerFormModal"
import {
  deleteCloudServer,
  listCloudServers,
  testSavedCloudServer,
  type CloudServer,
} from "../api/cloud_server"

const { Title, Paragraph, Text } = Typography

const PAGE_SKELETON: SkeletonSpec[] = [
  { type: "header", title: 220, subtitle: 280 },
  { type: "grid", cols: 4, count: 4, gap: 12, item: { type: "card", h: 90 } },
  { type: "table", rows: 6, cols: 6 },
]

const ACCOUNT_TYPE_META: Record<CloudServer["account_type"], { label: string; color: string }> = {
  admin: { label: "自营", color: "blue" },
  agent: { label: "资源池", color: "gold" },
  client: { label: "魔方财务", color: "green" },
  resource: { label: "财务资源池", color: "cyan" },
}

const STATUS_META: Record<CloudServer["status"], { label: string; color: string }> = {
  online: { label: "在线", color: "success" },
  offline: { label: "离线", color: "error" },
  unknown: { label: "未测试", color: "default" },
}

function endpoint(server: CloudServer) {
  return `${server.secure ? "https" : "http"}://${server.hostname}${server.port ? `:${server.port}` : ""}`
}

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

export default function AdminCloudServers() {
  const { token } = theme.useToken()
  const [loading, setLoading] = useState(true)
  const [servers, setServers] = useState<CloudServer[]>([])
  const [modalOpen, setModalOpen] = useState(false)
  const [editing, setEditing] = useState<CloudServer | null>(null)
  const [testingId, setTestingId] = useState<number | null>(null)

  const reload = useCallback(async (silent = false) => {
    if (!silent) setLoading(true)
    try {
      const res = await listCloudServers()
      setServers(res.data ?? [])
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载失败")
    } finally {
      setLoading(false)
    }
  }, [])

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

  const stats = useMemo(() => {
    const online = servers.filter((server) => server.status === "online").length
    const disabled = servers.filter((server) => server.disabled).length
    const admin = servers.filter((server) => server.account_type === "admin").length
    const agent = servers.filter((server) => server.account_type === "agent").length
    return { online, disabled, admin, agent }
  }, [servers])

  const openCreate = () => {
    setEditing(null)
    setModalOpen(true)
  }

  const openEdit = useCallback((server: CloudServer) => {
    setEditing(server)
    setModalOpen(true)
  }, [])

  const removeServer = useCallback(async (server: CloudServer) => {
    try {
      await deleteCloudServer(server.id)
      toast.success("已删除")
      await reload(true)
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "删除失败")
    }
  }, [reload])

  const testServer = useCallback(async (server: CloudServer) => {
    setTestingId(server.id)
    try {
      const res = await testSavedCloudServer(server.id)
      if (res.data?.ok) {
        toast.success(res.data.message)
      } else {
        toast.error(res.data?.message || "测试失败")
      }
      await reload(true)
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "测试请求失败")
    } finally {
      setTestingId(null)
    }
  }, [reload])

  const columns = useMemo<TableColumnsType<CloudServer>>(() => [
    {
      title: "接口",
      dataIndex: "name",
      width: 260,
      render: (_value, record) => (
        <Space size={12}>
          <Avatar
            shape="square"
            size={40}
            style={{ color: token.colorPrimary, background: token.colorPrimaryBg }}
            icon={<CloudServerOutlined />}
          />
          <Space orientation="vertical" size={0}>
            <Text strong>{record.name}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>ID {record.id}</Text>
          </Space>
        </Space>
      ),
    },
    {
      title: "类型",
      dataIndex: "account_type",
      width: 120,
      render: (value: CloudServer["account_type"]) => {
        const meta = ACCOUNT_TYPE_META[value] ?? { label: value || "未知", color: "default" }
        return <Tag color={meta.color}>{meta.label}</Tag>
      },
    },
    {
      title: "地址",
      key: "endpoint",
      width: 260,
      render: (_value, record) => (
        <Space orientation="vertical" size={0}>
          <Text code style={{ fontSize: 12 }}>{endpoint(record)}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.username}</Text>
        </Space>
      ),
    },
    {
      title: "客户 / 前缀",
      key: "client",
      width: 180,
      render: (_value, record) => (
        <Space orientation="vertical" size={0}>
          <Text>{record.client_id ? `客户 #${record.client_id}` : "-"}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.user_prefix || "无前缀"}</Text>
        </Space>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 220,
      render: (value: CloudServer["status"], record) => {
        const meta = STATUS_META[value] ?? { label: value || "未知", color: "default" }
        return (
          <Space orientation="vertical" size={0}>
            <Space size={6} wrap>
              <Tag color={meta.color}>{meta.label}</Tag>
              {record.disabled && <Tag color="red">已禁用</Tag>}
            </Space>
            {record.last_check_message && (
              <Text type="secondary" style={{ fontSize: 12 }} ellipsis={{ tooltip: record.last_check_message }}>
                {record.last_check_message}
              </Text>
            )}
          </Space>
        )
      },
    },
    {
      title: "最近检测",
      dataIndex: "last_check_at",
      width: 180,
      render: fmtDate,
    },
    {
      title: "操作",
      key: "action",
      width: 140,
      align: "right",
      render: (_value, record) => (
        <Space size={4}>
          <Tooltip title="测试连通性">
            <Button
              type="text"
              icon={<ThunderboltOutlined />}
              loading={testingId === record.id}
              onClick={() => testServer(record)}
            />
          </Tooltip>
          <Tooltip title="编辑接口">
            <Button type="text" icon={<EditOutlined />} onClick={() => openEdit(record)} />
          </Tooltip>
          <Popconfirm
            title={`删除接口「${record.name}」？`}
            okText="删除"
            cancelText="取消"
            okButtonProps={{ danger: true }}
            onConfirm={() => removeServer(record)}
          >
            <Tooltip title="删除接口">
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ], [openEdit, removeServer, testServer, testingId, token.colorPrimary, token.colorPrimaryBg])

  return (
    <PageSkeleton loading={loading} spec={PAGE_SKELETON} gap={24}>
      <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 }}>
              管理自营和资源池魔方云节点，供产品自动开通时绑定使用。
            </Paragraph>
          </Col>
          <Col>
            <Space wrap>
              <Button icon={<ReloadOutlined />} loading={loading} onClick={() => reload()}>
                刷新
              </Button>
              <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
                添加接口
              </Button>
            </Space>
          </Col>
        </Row>

        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} xl={6}>
            <Card variant="outlined">
              <Statistic title="接口总数" value={servers.length} suffix="个" prefix={<ApiOutlined />} />
            </Card>
          </Col>
          <Col xs={24} sm={12} xl={6}>
            <Card variant="outlined">
              <Statistic title="在线接口" value={stats.online} suffix="个" prefix={<CheckCircleOutlined />} styles={{ content: { color: token.colorSuccess } }} />
            </Card>
          </Col>
          <Col xs={24} sm={12} xl={6}>
            <Card variant="outlined">
              <Statistic title="自营 / 资源池" value={`${stats.admin} / ${stats.agent}`} prefix={<GlobalOutlined />} />
            </Card>
          </Col>
          <Col xs={24} sm={12} xl={6}>
            <Card variant="outlined">
              <Statistic title="已禁用" value={stats.disabled} suffix="个" prefix={<WarningOutlined />} styles={{ content: { color: token.colorWarning } }} />
            </Card>
          </Col>
        </Row>

        <Card variant="outlined" title={<Space><SafetyCertificateOutlined />接口列表</Space>}>
          <Table
            rowKey={(record) => String(record.id || `${record.server_type}:${record.hostname}:${record.username}`)}
            loading={loading}
            columns={columns}
            dataSource={servers}
            pagination={{ pageSize: 10, showSizeChanger: false }}
            scroll={{ x: 1360 }}
            locale={{
              emptyText: (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="尚未添加任何魔方云接口">
                  <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>添加接口</Button>
                </Empty>
              ),
            }}
          />
        </Card>
      </Space>

      <CloudServerFormModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        onSaved={() => reload(true)}
        initial={editing}
      />
    </PageSkeleton>
  )
}
