'use client'

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

const statusLabel: Record<string, string> = {
  ok: '通过',
  warning: '警告',
  error: '阻断',
}

function statusClass(status: string) {
  if (status === 'ok') return 'bg-green-50 text-green'
  if (status === 'warning') return 'bg-amber-50 text-amber-700'
  return 'bg-red-50 text-red-700'
}

function StatusIcon({ status }: { status: string }) {
  if (status === 'ok') return <CheckCircle2 className="h-4 w-4 text-green" />
  if (status === 'warning') return <AlertTriangle className="h-4 w-4 text-amber-600" />
  return <XCircle className="h-4 w-4 text-red-600" />
}

export default function AdminConfigChecksPage() {
  const [items, setItems] = useState<BackendSystemConfigCheck[]>([])
  const [summary, setSummary] = useState<Record<string, number>>({})
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const grouped = useMemo(() => items.reduce<Record<string, BackendSystemConfigCheck[]>>((groups, item) => {
    groups[item.group] = [...(groups[item.group] || []), item]
    return groups
  }, {}), [items])

  async function reload() {
    setLoading(true)
    try {
      const result = await backend.adminSystemConfigChecks()
      setItems(result.items)
      setSummary(result.summary)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '配置检查加载失败')
    } finally {
      setLoading(false)
    }
  }

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

  return (
    <AdminShell
      title="配置检查"
      description="上线前检查安全、支付、文件、网络和登录配置；只读展示，不直接修改环境变量。"
      topbarMetrics={[
        { label: '检查项', value: summary.total || items.length },
        { label: '通过', value: summary.ok || 0 },
        { label: '警告', value: summary.warning || 0 },
        { label: '阻断', value: summary.error || 0 },
      ]}
    >
      {error && <div className="mb-3 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}

      <section className="grid h-[calc(100vh-142px)] min-h-[560px] grid-rows-[auto_1fr] gap-3 overflow-hidden">
        <div className="flex flex-wrap items-center justify-between gap-2 border border-line bg-white px-3 py-2.5">
          <div className="text-sm font-extrabold text-ink">配置检查结果</div>
          <div className="flex flex-wrap gap-2">
            <Link href="/admin/system" className="h-9 rounded-[4px] border border-line px-3 py-2 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">系统健康</Link>
            <button type="button" onClick={() => void reload()} disabled={loading} className="inline-flex h-9 items-center gap-2 rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand disabled:opacity-60">
              <RefreshCw className="h-4 w-4" />
              {loading ? '刷新中' : '刷新'}
            </button>
          </div>
        </div>

        <div className="min-h-0 space-y-3 overflow-y-auto">
          {Object.entries(grouped).map(([group, checks]) => (
            <section key={group} className="border border-line bg-white">
              <div className="border-b border-line bg-bg px-3 py-2 text-sm font-extrabold text-ink">{group}</div>
              <div className="divide-y divide-line">
                {checks.map((item) => (
                  <div key={item.key} className="grid gap-3 px-3 py-3 lg:grid-cols-[180px_110px_minmax(0,1fr)_minmax(0,1fr)] lg:items-start">
                    <div className="flex items-center gap-2">
                      <StatusIcon status={item.status} />
                      <span className="text-sm font-extrabold text-ink">{item.label}</span>
                    </div>
                    <span className={`w-fit rounded-[4px] px-2 py-1 text-xs font-extrabold ${statusClass(item.status)}`}>{statusLabel[item.status] || item.status}</span>
                    <div className="text-xs font-bold leading-5 text-muted">{item.message}</div>
                    <div className="text-xs font-bold leading-5 text-muted">{item.suggestion || '-'}</div>
                  </div>
                ))}
              </div>
            </section>
          ))}
          {!loading && items.length === 0 && <div className="border border-line bg-white px-5 py-8 text-sm font-bold text-muted">暂无配置检查结果</div>}
        </div>
      </section>
    </AdminShell>
  )
}

