'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { Activity, RefreshCw } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendHealthDeep } from '@/lib/backend'

const statusLabel: Record<string, string> = {
  ok: '正常',
  degraded: '降级',
  warning: '警告',
  error: '异常',
}

function statusClass(status: string) {
  if (status === 'ok') return 'bg-emerald-50 text-emerald-700'
  if (status === 'warning' || status === 'degraded') return 'bg-yellow-50 text-yellow-700'
  return 'bg-red-50 text-red-700'
}

function formatDate(value?: string) {
  if (!value) return '-'
  return new Date(value).toLocaleString('zh-CN')
}

function checkMessage(key: string, check: BackendHealthDeep['checks'][string]) {
  if (key === 'objectStorage' && check.driver === 'local' && check.required === false) {
    return '本地上传模式已启用，生产上线前配置 S3 对象存储。'
  }
  return check.message || check.code || '检查项可用'
}

function configuredLabel(key: string, check: BackendHealthDeep['checks'][string]) {
  if (key === 'objectStorage' && check.driver === 'local' && check.required === false) return '本地模式'
  return check.configured ? '已配置' : '未配置'
}

export default function AdminSystemPage() {
  const [health, setHealth] = useState<BackendHealthDeep | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const checks = useMemo(() => Object.entries(health?.checks || {}), [health])

  async function reload() {
    setLoading(true)
    try {
      const result = await backend.adminSystemHealth()
      setHealth(result)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '系统健康加载失败')
    } finally {
      setLoading(false)
    }
  }

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

  return (
    <AdminShell title="系统健康" description="查看运行时健康状态；上线配置风险请到配置检查，人工任务请到运维任务。">
      {error && <div className="mb-3 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}

      <div className="grid h-[calc(100vh-104px)] min-h-[560px] grid-rows-[auto_1fr] gap-3 overflow-hidden">
        <section className="flex flex-col gap-3 border border-line bg-white p-3 md:flex-row md:items-center md:justify-between">
          <div className="flex items-center gap-3">
            <div className={`flex h-9 w-9 items-center justify-center ${statusClass(health?.status || 'warning')}`}>
              <Activity className="h-5 w-5" />
            </div>
            <div>
              <div className="text-base font-extrabold text-ink">{statusLabel[health?.status || ''] || health?.status || '未加载'}</div>
              <div className="mt-1 text-xs font-bold text-muted">最后检查：{formatDate(health?.timestamp)} · {health?.service || 'dlbdi-backend'} · {health?.mode || '-'}</div>
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href="/admin/ops/config-checks" className="inline-flex h-9 items-center justify-center rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
              配置检查
            </Link>
            <Link href="/admin/ops/jobs" className="inline-flex h-9 items-center justify-center rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
              运维任务
            </Link>
            <button type="button" onClick={() => void reload()} disabled={loading} className="inline-flex h-9 items-center justify-center gap-2 rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand disabled:opacity-60">
              <RefreshCw className="h-4 w-4" />
              {loading ? '刷新中' : '刷新'}
            </button>
          </div>
        </section>

        <section className="grid min-h-0 auto-rows-min gap-3 overflow-y-auto md:grid-cols-2">
          {checks.map(([key, check]) => (
            <div key={key} className="border border-line bg-white p-3">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-extrabold text-ink">{key}</div>
                  <div className="mt-1 text-xs font-bold text-muted">{checkMessage(key, check)}</div>
                </div>
                <span className={`shrink-0 px-2 py-1 text-xs font-extrabold ${statusClass(check.status)}`}>{statusLabel[check.status] || check.status}</span>
              </div>
              <dl className="mt-3 grid grid-cols-2 gap-3 text-xs">
                {'configured' in check && (
                  <div>
                    <dt className="font-bold text-soft">配置</dt>
                    <dd className="mt-1 font-extrabold text-ink">{configuredLabel(key, check)}</dd>
                  </div>
                )}
                {'driver' in check && (
                  <div>
                    <dt className="font-bold text-soft">模式</dt>
                    <dd className="mt-1 font-extrabold text-ink">{check.driver === 'local' ? '本地上传' : String(check.driver || '-')}</dd>
                  </div>
                )}
                {'enabled' in check && (
                  <div>
                    <dt className="font-bold text-soft">启用</dt>
                    <dd className="mt-1 font-extrabold text-ink">{check.enabled ? '已启用' : '未启用'}</dd>
                  </div>
                )}
                {'latencyMs' in check && (
                  <div>
                    <dt className="font-bold text-soft">探测耗时</dt>
                    <dd className="mt-1 font-extrabold text-ink">{String(check.latencyMs)} ms</dd>
                  </div>
                )}
              </dl>
            </div>
          ))}
          {!checks.length && <div className="border border-line bg-white px-4 py-8 text-sm font-bold text-muted">暂无系统检查数据</div>}
        </section>
      </div>
    </AdminShell>
  )
}
