import { useCallback, useEffect, useMemo, useState } from "react"
import type { ReactNode } from "react"

import {
  CheckCircleOutlined,
  CloudDownloadOutlined,
  DatabaseOutlined,
  ReloadOutlined,
  SafetyCertificateOutlined,
  WarningOutlined,
} from "@ant-design/icons"
import {
  Alert,
  Badge,
  Button,
  Card,
  Col,
  Grid,
  Row,
  Skeleton,
  Space,
  Tag,
  Typography,
  message,
  theme,
} from "antd"
import { getAdminSystemInfo, type AdminSystemInfo, type ServiceStatus } from "../api/system"

const { Title, Text, Paragraph, Link } = Typography

type SectionKey = "license" | "status" | "update"

interface SectionMeta {
  key: SectionKey
  title: string
  description: string
  icon: ReactNode
  badge: ReactNode
}

// ─── Tag helpers ────────────────────────────────────────────────────────────

function statusTag(status?: ServiceStatus) {
  if (status === "ok") return <Tag color="success">正常</Tag>
  if (status === "disabled") return <Tag>未启用</Tag>
  if (status === "error") return <Tag color="error">异常</Tag>
  return <Tag>{status || "未知"}</Tag>
}

function boolTag(value?: boolean) {
  return value ? <Tag color="success">已启用</Tag> : <Tag>未启用</Tag>
}

function yesNoTag(value?: boolean, yesText = "是", noText = "否") {
  if (value == null) return <Tag>未知</Tag>
  return value ? <Tag color="error">{yesText}</Tag> : <Tag color="success">{noText}</Tag>
}

function licenseStatusTag(info: AdminSystemInfo | null) {
  const backend = backendType(info)
  if (backend === "python") return <Tag color="blue">开源版</Tag>
  if (backend !== "go") return <Tag>未知</Tag>
  if (info?.license?.status === "active") return <Tag color="success">授权有效</Tag>
  if (!info?.license?.configured || info?.license?.status === "missing") return <Tag color="error">未填写</Tag>
  if (info?.license?.status === "invalid") return <Tag color="error">无效</Tag>
  return <Tag color="warning">不可用</Tag>
}

// ─── Data helpers ────────────────────────────────────────────────────────────

function backendType(info: AdminSystemInfo | null) {
  const explicit = (info?.app.backend_type || "").toLowerCase()
  if (explicit === "go" || explicit === "python") return explicit
  if (info?.runtime?.go_version) return "go"
  if (info) return "python"
  return "unknown"
}

function editionLabel(info: AdminSystemInfo | null) {
  const b = backendType(info)
  if (b === "go") return "商业版"
  if (b === "python") return "开源版"
  return "未知版本"
}

function backendLabel(info: AdminSystemInfo | null) {
  const b = backendType(info)
  if (b === "go") return "Go"
  if (b === "python") return "Python"
  return "未知"
}

function licenseTypeLabel(value?: string) {
  if (!value) return "-"
  if (value.toLowerCase() === "standard") return "标准版"
  return value
}

function changelogText(value?: string | null) {
  if (!value || value.toLowerCase() === "none") return "暂无更新说明"
  return value
}

function errorMessage(error: unknown, fallback: string) {
  return (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail || fallback
}

function formatDateTime(value?: string) {
  if (!value) return "-"
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return new Intl.DateTimeFormat("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  }).format(date)
}

function formatPeriod(start?: string, end?: string) {
  if (start && end) return `${start} 至 ${end}`
  if (start) return `${start} 起，永久有效`
  if (end) return `截至 ${end}`
  return "-"
}

function platformLabel(system?: string, arch?: string) {
  const labels: Record<string, string> = { windows: "Windows", linux: "Linux", darwin: "macOS" }
  const name = system ? labels[system.toLowerCase()] || system : "未知系统"
  return arch ? `${name} / ${arch}` : name
}

function formatUptime(seconds?: number) {
  if (seconds == null || seconds < 0) return "-"
  const d = Math.floor(seconds / 86400)
  const h = Math.floor((seconds % 86400) / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  if (d > 0) return `${d} 天 ${h} 小时`
  if (h > 0) return `${h} 小时 ${m} 分钟`
  return `${m} 分钟`
}

// ─── Sub-components ──────────────────────────────────────────────────────────

function NavItem({
  active,
  item,
  onClick,
}: {
  active: boolean
  item: SectionMeta
  onClick: () => void
}) {
  const { token } = theme.useToken()
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        all: "unset",
        display: "flex",
        alignItems: "center",
        gap: 10,
        width: "100%",
        padding: "10px 12px",
        borderRadius: 8,
        cursor: "pointer",
        background: active ? token.colorPrimaryBg : "transparent",
        border: `1px solid ${active ? token.colorPrimaryBorder : "transparent"}`,
        transition: "all 0.15s",
        boxSizing: "border-box",
      }}
    >
      <span style={{ fontSize: 16, color: active ? token.colorPrimary : token.colorTextTertiary, lineHeight: 1, flexShrink: 0 }}>
        {item.icon}
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div>
          <Text strong style={{ fontSize: 13, color: active ? token.colorPrimary : token.colorText }}>
            {item.title}
          </Text>
        </div>
        <div>
          <Text type="secondary" style={{ fontSize: 11 }}>{item.description}</Text>
        </div>
      </div>
      <div style={{ flexShrink: 0 }}>{item.badge}</div>
    </button>
  )
}

function FieldRow({ label, value }: { label: string; value: ReactNode }) {
  const { token } = theme.useToken()
  return (
    <div
      style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        minHeight: 38,
        padding: "7px 0",
        borderBottom: `1px solid ${token.colorBorderSecondary}`,
        gap: 32,
      }}
    >
      <Text style={{ fontSize: 13, flexShrink: 0, whiteSpace: "nowrap", color: token.colorTextSecondary }}>
        {label}
      </Text>
      <div style={{ fontSize: 13, textAlign: "right", wordBreak: "break-word", color: token.colorText }}>
        {typeof value === "string" ? <span>{value}</span> : value}
      </div>
    </div>
  )
}

function FieldGroup({ children }: { children: ReactNode }) {
  const { token } = theme.useToken()
  return (
    <div style={{ borderTop: `1px solid ${token.colorBorderSecondary}` }}>
      {children}
    </div>
  )
}

function GroupLabel({ title, description }: { title: string; description?: string }) {
  const { token } = theme.useToken()
  return (
    <div style={{ padding: "14px 0 4px" }}>
      <Text style={{ fontSize: 12, fontWeight: 600, color: token.colorTextSecondary }}>
        {title}
      </Text>
      {description && (
        <Text type="secondary" style={{ fontSize: 12, marginLeft: 8 }}>{description}</Text>
      )}
    </div>
  )
}

// ─── Main component ──────────────────────────────────────────────────────────

export default function AdminSystemInfo() {
  const { token } = theme.useToken()
  const screens = Grid.useBreakpoint()
  const [loading, setLoading] = useState(true)
  const [info, setInfo] = useState<AdminSystemInfo | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [activeSection, setActiveSection] = useState<SectionKey>("license")

  const load = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await getAdminSystemInfo()
      setInfo(res.data ?? null)
    } catch (e: unknown) {
      const detail = errorMessage(e, "加载系统信息失败")
      setError(detail)
      message.error(detail)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    void load()
    const handleLicenseUpdated = () => void load()
    window.addEventListener("admin-license-updated", handleLicenseUpdated)
    return () => window.removeEventListener("admin-license-updated", handleLicenseUpdated)
  }, [load])

  const sections = useMemo<SectionMeta[]>(() => {
    const dbOk = info?.database.status === "ok"
    const redisOk = info?.redis.status === "ok"
    return [
      {
        key: "license",
        title: "授权信息",
        description: "授权状态与服务期限",
        icon: <SafetyCertificateOutlined />,
        badge: licenseStatusTag(info),
      },
      {
        key: "status",
        title: "系统状态",
        description: "运行环境与核心依赖",
        icon: <DatabaseOutlined />,
        badge: statusTag(dbOk && redisOk ? "ok" : "error"),
      },
      {
        key: "update",
        title: "更新信息",
        description: "版本发布与升级要求",
        icon: <CloudDownloadOutlined />,
        badge: info?.update?.version
          ? <Tag style={{ margin: 0 }}>{`v${info.update.version}`}</Tag>
          : <Tag style={{ margin: 0 }}>未知</Tag>,
      },
    ]
  }, [info])

  if (loading && !info) {
    return (
      <Space direction="vertical" size={16} style={{ width: "100%" }}>
        <Skeleton.Input active style={{ width: 200, height: 36 }} />
        <Card variant="outlined" styles={{ body: { padding: 0 } }}>
          <Row>
            <Col xs={24} md={8} xl={6}>
              <div style={{ padding: 12 }}>
                <Space direction="vertical" size={8} style={{ width: "100%" }}>
                  <Skeleton.Button active block style={{ height: 64, borderRadius: 8 }} />
                  <Skeleton.Button active block style={{ height: 64, borderRadius: 8 }} />
                  <Skeleton.Button active block style={{ height: 64, borderRadius: 8 }} />
                </Space>
              </div>
            </Col>
            <Col xs={24} md={16} xl={18}>
              <div style={{ padding: "28px 32px" }}>
                <Skeleton active paragraph={{ rows: 8 }} />
              </div>
            </Col>
          </Row>
        </Card>
      </Space>
    )
  }

  const paneStyle = screens.md
    ? { height: "calc(100vh - 220px)", minHeight: 440, maxHeight: 700, overflowY: "auto" as const }
    : {}

  const isAllOk = info?.database.status === "ok" && info?.redis.status === "ok"

  const licenseContent = (
    <div style={{ width: "100%" }}>
      <div
        style={{
          background: token.colorFillAlter,
          borderRadius: 8,
          padding: "14px 16px",
          marginBottom: 16,
          display: "flex",
          alignItems: "flex-start",
          justifyContent: "space-between",
          gap: 12,
          flexWrap: "wrap",
        }}
      >
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
            <Title level={4} style={{ margin: 0 }}>
              {editionLabel(info)}{info?.license?.version ? ` v${info.license.version}` : ""}
            </Title>
            {licenseStatusTag(info)}
          </div>
          {info?.license?.license_no ? (
            <Text
              type="secondary"
              copyable={{ text: info.license.license_no }}
              style={{ fontFamily: "ui-monospace, SFMono-Regular, Consolas, monospace", fontSize: 12 }}
            >
              {info.license.license_no}
            </Text>
          ) : (
            <Text type="secondary" style={{ fontSize: 12 }}>尚无授权编号</Text>
          )}
        </div>
        {info?.license?.status === "active" && (
          <Space size={5}>
            <CheckCircleOutlined style={{ color: token.colorSuccess, fontSize: 13 }} />
            <Text type="secondary" style={{ fontSize: 12 }}>已同步</Text>
          </Space>
        )}
      </div>

      <FieldGroup>
        <FieldRow label="授权方案" value={licenseTypeLabel(info?.license?.type)} />
        <FieldRow label="授权期限" value={info?.license?.expire || "永久"} />
        <FieldRow label="购买日期" value={info?.license?.purchase || "-"} />
        <FieldRow label="更新服务" value={formatPeriod(info?.license?.service_purchase, info?.license?.service_expire)} />
        <FieldRow label="最近验证" value={formatDateTime(info?.license?.verified_at)} />
      </FieldGroup>

      <GroupLabel title="实例绑定" description="商业版服务上报的运行环境" />
      <FieldGroup>
        <FieldRow label="实例名称" value={info?.license?.instance_name || "-"} />
        <FieldRow label="运行平台" value={platformLabel(info?.license?.system_name, info?.license?.system_arch)} />
        <FieldRow label="绑定地址" value={info?.license?.backend_url || "未绑定"} />
        <FieldRow label="运行版本" value={info?.license?.running_version || info?.app.version || "-"} />
        <FieldRow label="最后在线" value={formatDateTime(info?.license?.last_online)} />
      </FieldGroup>
    </div>
  )

  const statusContent = (
    <div style={{ width: "100%" }}>
      <div
        style={{
          background: isAllOk ? token.colorSuccessBg : token.colorErrorBg,
          border: `1px solid ${isAllOk ? token.colorSuccessBorder : token.colorErrorBorder}`,
          borderRadius: 8,
          padding: "10px 16px",
          marginBottom: 16,
          display: "flex",
          alignItems: "center",
          gap: 10,
        }}
      >
        <Badge status={isAllOk ? "success" : "error"} />
        <Text style={{ color: isAllOk ? token.colorSuccess : token.colorError, fontWeight: 500, fontSize: 13 }}>
          {isAllOk ? "所有服务运行正常" : "部分服务存在异常"}
        </Text>
      </div>

      <FieldGroup>
        <FieldRow label="后端类型" value={backendLabel(info)} />
        <FieldRow label="应用版本" value={info?.app.version || "-"} />
        <FieldRow label="Go 运行时" value={info?.runtime?.go_version || "-"} />
        <FieldRow label="系统平台" value={platformLabel(info?.runtime?.os, info?.runtime?.arch)} />
        <FieldRow label="CPU 核心" value={String(info?.runtime?.cpus ?? "-")} />
        <FieldRow label="运行时间" value={formatUptime(info?.app.uptime_seconds)} />
        <FieldRow
          label="内存占用"
          value={info?.runtime?.memory.alloc_mb != null ? `${info.runtime.memory.alloc_mb.toFixed(1)} MB` : "-"}
        />
      </FieldGroup>

      <GroupLabel title="核心服务" />
      <FieldGroup>
        <FieldRow label="MySQL" value={statusTag(info?.database.status)} />
        <FieldRow label="Redis" value={statusTag(info?.redis.status)} />
        <FieldRow label="插件运行时" value={boolTag(info?.plugins.enabled)} />
      </FieldGroup>
    </div>
  )

  const updateContent = (
    <div style={{ width: "100%" }}>
      {info?.update?.force_update_required && (
        <Alert type="error" showIcon icon={<WarningOutlined />} message="当前版本需要强制更新" style={{ marginBottom: 12, borderRadius: 8 }} />
      )}
      {info?.update?.db_update_required && (
        <Alert type="warning" showIcon message="本次更新包含数据库升级" style={{ marginBottom: 12, borderRadius: 8 }} />
      )}

      <FieldGroup>
        <FieldRow label="当前版本" value={info?.app.version || "-"} />
        <FieldRow
          label="最新版本"
          value={info?.update?.version ? <Tag color="blue" style={{ margin: 0 }}>{`v${info.update.version}`}</Tag> : "-"}
        />
        <FieldRow label="发布时间" value={info?.update?.update_time || "-"} />
        <FieldRow label="数据库升级" value={yesNoTag(info?.update?.db_update_required, "需要", "不需要")} />
        <FieldRow label="强制更新" value={yesNoTag(info?.update?.force_update_required, "强制", "不强制")} />
        <FieldRow
          label="下载地址"
          value={
            info?.update?.update_url ? (
              <Link href={info.update.update_url} target="_blank" rel="noreferrer">
                <Space size={4}><CloudDownloadOutlined /><span>下载更新</span></Space>
              </Link>
            ) : "-"
          }
        />
      </FieldGroup>

      <GroupLabel title="更新说明" />
      <div style={{ background: token.colorFillAlter, borderRadius: 8, padding: "10px 14px", marginTop: 4 }}>
        <Paragraph style={{ margin: 0, whiteSpace: "pre-wrap", fontSize: 13, color: token.colorText, lineHeight: "1.8" }}>
          {changelogText(info?.update?.changelog)}
        </Paragraph>
      </div>
    </div>
  )

  const contentMap: Record<SectionKey, ReactNode> = {
    license: licenseContent,
    status: statusContent,
    update: updateContent,
  }

  const activeMeta = sections.find((s) => s.key === activeSection) ?? sections[0]

  return (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
        <div>
          <Title level={3} style={{ margin: 0 }}>系统信息</Title>
          <Text type="secondary">授权、运行状态与版本更新</Text>
        </div>
        <Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>
          刷新
        </Button>
      </div>

      {error && <Alert type="error" showIcon message={error} style={{ borderRadius: 8 }} />}

      <Card variant="outlined" styles={{ body: { padding: 0 } }}>
        <Row gutter={0}>
          {/* Left nav */}
          <Col
            xs={24} md={7} xl={6}
            style={{
              borderRight: screens.md ? `1px solid ${token.colorBorderSecondary}` : "none",
              borderBottom: !screens.md ? `1px solid ${token.colorBorderSecondary}` : "none",
            }}
          >
            <div style={{ ...paneStyle, padding: 10 }}>
              <Space direction="vertical" size={4} style={{ width: "100%" }}>
                {sections.map((item) => (
                  <NavItem
                    key={item.key}
                    active={item.key === activeSection}
                    item={item}
                    onClick={() => setActiveSection(item.key)}
                  />
                ))}
              </Space>
            </div>
          </Col>

          {/* Right content */}
          <Col xs={24} md={17} xl={18}>
            <div style={{ ...paneStyle, padding: screens.md ? "24px 28px" : "20px 16px" }}>
              {/* Section header */}
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 10,
                  marginBottom: 20,
                  paddingBottom: 16,
                  borderBottom: `1px solid ${token.colorBorderSecondary}`,
                }}
              >
                <div
                  style={{
                    width: 36,
                    height: 36,
                    borderRadius: 8,
                    background: token.colorPrimaryBg,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    color: token.colorPrimary,
                    fontSize: 16,
                    flexShrink: 0,
                  }}
                >
                  {activeMeta.icon}
                </div>
                <div>
                  <Text strong style={{ fontSize: 15, display: "block", lineHeight: "1.3" }}>{activeMeta.title}</Text>
                  <Text type="secondary" style={{ fontSize: 12 }}>{activeMeta.description}</Text>
                </div>
              </div>

              {contentMap[activeSection]}
            </div>
          </Col>
        </Row>
      </Card>
    </Space>
  )
}
