import { useEffect, useState } from 'react'
import { Card, Descriptions, Skeleton, Typography } from 'antd'
import { inventoryApi } from '@/lib/api'

function renderValue(value: unknown) {
  if (value === null || value === undefined) {
    return '-'
  }

  if (typeof value === 'object') {
    return (
      <pre style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
        {JSON.stringify(value, null, 2)}
      </pre>
    )
  }

  return String(value)
}

export function ServerStatePage() {
  const [server, setServer] = useState<Record<string, unknown> | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let ignore = false

    inventoryApi
      .getServerInfo()
      .then((response) => {
        if (!ignore) {
          setServer(response.data.server)
        }
      })
      .finally(() => {
        if (!ignore) {
          setLoading(false)
        }
      })

    return () => {
      ignore = true
    }
  }, [])

  return (
    <div className="page-stack">
      <Card className="glass-panel page-panel">
        <Typography.Title level={2} style={{ marginBottom: 8 }}>
          服务器状态
        </Typography.Title>
        <Typography.Paragraph className="text-muted" style={{ marginBottom: 0 }}>
          该页面直接读取 `/system/getServerInfo` 的结构化结果，不预设字段，优先保证信息完整。
        </Typography.Paragraph>
      </Card>
      <Card className="glass-panel page-panel">
        {loading ? (
          <Skeleton active />
        ) : (
          <Descriptions bordered column={1} size="middle">
            {Object.entries(server || {}).map(([key, value]) => (
              <Descriptions.Item key={key} label={key}>
                {renderValue(value)}
              </Descriptions.Item>
            ))}
          </Descriptions>
        )}
      </Card>
    </div>
  )
}
