'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { AlertTriangle, ArrowRight, CheckCircle2, Eye, RefreshCw, RotateCcw, Search, XCircle } from 'lucide-react'
import { AdminMetricPanel } from '@/components/admin/AdminMetrics'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendOperationalEvent, type BackendOperationalEventSeverity, type BackendOperationalEventStatus } from '@/lib/backend'

const statusOptions: { label: string; value: '' | BackendOperationalEventStatus }[] = [
  { label: '全部状态', value: '' },
  { label: '待处理', value: 'open' },
  { label: '处理中', value: 'acknowledged' },
  { label: '已解决', value: 'resolved' },
  { label: '已忽略', value: 'ignored' },
]

const severityOptions: { label: string; value: '' | BackendOperationalEventSeverity }[] = [
  { label: '全部级别', value: '' },
  { label: '严重', value: 'critical' },
  { label: '错误', value: 'error' },
  { label: '警告', value: 'warning' },
  { label: '信息', value: 'info' },
]

const statusLabel: Record<string, string> = {
  open: '待处理',
  acknowledged: '处理中',
  resolved: '已解决',
  ignored: '已忽略',
}

const severityLabel: Record<string, string> = {
  critical: '严重',
  error: '错误',
  warning: '警告',
  info: '信息',
}

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

function severityClass(severity: string) {
  if (severity === 'critical') return 'bg-red-50 text-red-700'
  if (severity === 'error') return 'bg-amber-50 text-amber-700'
  if (severity === 'warning') return 'bg-yellow-50 text-yellow-700'
  return 'bg-bg text-muted'
}

function statusClass(status: string) {
  if (status === 'open') return 'bg-red-50 text-red-700'
  if (status === 'acknowledged') return 'bg-brand-light text-brand'
  if (status === 'resolved') return 'bg-emerald-50 text-emerald-700'
  return 'bg-bg text-muted'
}

function stringifyPayload(payload?: Record<string, unknown>) {
  if (!payload || Object.keys(payload).length === 0) return '无上下文'
  return JSON.stringify(payload, null, 2)
}

export default function AdminExceptionsPage() {
  const [items, setItems] = useState<BackendOperationalEvent[]>([])
  const [selectedId, setSelectedId] = useState('')
  const [summary, setSummary] = useState({ open: 0, acknowledged: 0, resolved: 0, critical: 0, error: 0 })
  const [total, setTotal] = useState(0)
  const [q, setQ] = useState('')
  const [status, setStatus] = useState('')
  const [severity, setSeverity] = useState('')
  const [note, setNote] = useState('')
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  const selected = useMemo(() => items.find((item) => item.id === selectedId) || items[0] || null, [items, selectedId])

  async function reload(next = { q, status, severity }) {
    setLoading(true)
    try {
      const result = await backend.adminOperationalEvents(next)
      setItems(result.items || [])
      setSummary(result.summary || { open: 0, acknowledged: 0, resolved: 0, critical: 0, error: 0 })
      setTotal(result.total || 0)
      setSelectedId((current) => current && result.items.some((item) => item.id === current) ? current : result.items[0]?.id || '')
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '异常事件加载失败')
    } finally {
      setLoading(false)
    }
  }

  async function mutate(action: 'acknowledge' | 'resolve' | 'ignore' | 'retry') {
    if (!selected) return
    if ((action === 'resolve' || action === 'ignore') && !note.trim()) {
      setError('解决或忽略异常必须填写处理备注')
      return
    }
    setSaving(true)
    try {
      if (action === 'retry') await backend.retryAdminOperationalEvent(selected.id, { note })
      if (action === 'acknowledge') await backend.updateAdminOperationalEvent(selected.id, { status: 'acknowledged', note })
      if (action === 'resolve') await backend.resolveAdminOperationalEvent(selected.id, { status: 'resolved', note })
      if (action === 'ignore') await backend.resolveAdminOperationalEvent(selected.id, { status: 'ignored', note })
      setNote('')
      await reload({ q, status, severity })
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '异常处理失败')
    } finally {
      setSaving(false)
    }
  }

  useEffect(() => {
    void reload()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <AdminShell title="异常处理中心" description="集中查看并处理订单、支付、短信、发票、文件和监控告警异常。">
      <div className="flex h-[calc(100vh-88px)] flex-col gap-2 overflow-hidden">
        {error && <div className="shrink-0 rounded-[4px] bg-red-50 px-3 py-2 text-xs font-bold text-red-700">{error}</div>}

        <AdminMetricPanel
          items={[
            { label: '待处理', value: summary.open },
            { label: '处理中', value: summary.acknowledged },
            { label: '严重', value: summary.critical },
            { label: '错误', value: summary.error },
            { label: '总数', value: total },
          ]}
        />

        <section className="flex min-h-0 flex-1 flex-col border border-line bg-white">
          <form className="flex shrink-0 flex-col gap-2 border-b border-line px-3 py-2 lg:flex-row lg:items-center" onSubmit={(event) => { event.preventDefault(); void reload({ q, status, severity }) }}>
          <div className="relative min-w-0 flex-1">
            <Search className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-soft" />
            <input
              value={q}
              onChange={(event) => setQ(event.target.value)}
              placeholder="搜索异常类型、对象、编号或错误信息"
              className="h-9 w-full rounded-[4px] border border-line pl-9 pr-3 text-xs outline-none focus:border-brand"
            />
          </div>
          <select value={severity} onChange={(event) => { setSeverity(event.target.value); void reload({ q, status, severity: event.target.value }) }} className="h-9 shrink-0 rounded-[4px] border border-line px-2 text-xs font-bold outline-none focus:border-brand">
            {severityOptions.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
          </select>
          <select value={status} onChange={(event) => { setStatus(event.target.value); void reload({ q, status: event.target.value, severity }) }} className="h-9 shrink-0 rounded-[4px] border border-line px-2 text-xs font-bold outline-none focus:border-brand">
            {statusOptions.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
          </select>
          <button className="h-9 shrink-0 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white">查询</button>
          <button type="button" onClick={() => void reload({ q, status, severity })} className="inline-flex h-9 shrink-0 items-center justify-center gap-1.5 rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
            <RefreshCw className="h-3.5 w-3.5" />
            刷新
          </button>
        </form>

        <div className="grid min-h-0 flex-1 gap-0 xl:grid-cols-[minmax(0,1fr)_360px]">
          <div className="flex min-h-0 flex-col border-r border-line">
            <div className="hidden grid-cols-[72px_88px_1fr_150px_128px] border-b border-line px-3 py-2 text-[11px] font-extrabold text-soft lg:grid">
              <span>级别</span><span>状态</span><span>异常</span><span>对象</span><span>发生时间</span>
            </div>
            <div className="min-h-0 flex-1 overflow-auto">
              {loading && <div className="px-3 py-8 text-xs font-bold text-muted">正在加载异常事件...</div>}
              {!loading && items.length === 0 && <div className="px-3 py-8 text-xs font-bold text-muted">暂无异常事件</div>}
              {!loading && items.map((item) => (
                <button
                  type="button"
                  key={item.id}
                  onClick={() => { setSelectedId(item.id); setNote(item.handlerNote || '') }}
                  className={`grid w-full gap-2 border-b border-line px-3 py-1.5 text-left text-xs hover:bg-bg lg:grid-cols-[72px_88px_1fr_150px_128px] lg:items-center ${selected?.id === item.id ? 'bg-brand-light' : 'bg-white'}`}
                >
                  <span className={`inline-flex h-6 w-fit items-center px-2 text-[11px] font-extrabold ${severityClass(item.severity)}`}>{severityLabel[item.severity] || item.severity}</span>
                  <span className={`inline-flex h-6 w-fit items-center px-2 text-[11px] font-extrabold ${statusClass(item.status)}`}>{statusLabel[item.status] || item.status}</span>
                  <span className="min-w-0">
                    <span className="block truncate font-extrabold text-ink">{item.message || item.eventType}</span>
                    <span className="mt-0.5 block truncate text-[11px] font-bold text-muted">{item.eventType}</span>
                  </span>
                  <span className="truncate text-[11px] font-bold text-muted">{item.resourceType || '-'} {item.resourceId || ''}</span>
                  <span className="text-[11px] font-bold text-muted">{formatDate(item.createdAt)}</span>
                </button>
              ))}
            </div>
          </div>

          <aside className="min-h-0 overflow-auto bg-bg/40 p-3">
            {!selected && <div className="text-xs font-bold text-muted">选择左侧异常事件后查看详情。</div>}
            {selected && (
              <div className="space-y-3">
                <div className="flex items-start gap-3">
                  <div className={`flex h-9 w-9 shrink-0 items-center justify-center ${severityClass(selected.severity)}`}>
                    <AlertTriangle className="h-4 w-4" />
                  </div>
                  <div className="min-w-0">
                    <div className="text-sm font-extrabold text-ink">{selected.message || selected.eventType}</div>
                    <div className="mt-1 text-[11px] font-bold text-muted">{selected.eventType} · {formatDate(selected.createdAt)}</div>
                  </div>
                </div>

                {selected.linkedHref && (
                  <Link href={selected.linkedHref} className="inline-flex h-8 w-full items-center justify-center gap-1.5 rounded-[4px] border border-line bg-white text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
                    打开关联单据
                    <ArrowRight className="h-3.5 w-3.5" />
                  </Link>
                )}

                <dl className="grid grid-cols-2 gap-2 text-xs">
                  <div>
                    <dt className="text-[11px] font-bold text-soft">级别</dt>
                    <dd className="mt-1 font-extrabold text-ink">{severityLabel[selected.severity] || selected.severity}</dd>
                  </div>
                  <div>
                    <dt className="text-[11px] font-bold text-soft">状态</dt>
                    <dd className="mt-1 font-extrabold text-ink">{statusLabel[selected.status] || selected.status}</dd>
                  </div>
                  <div>
                    <dt className="text-[11px] font-bold text-soft">对象类型</dt>
                    <dd className="mt-1 break-words font-extrabold text-ink">{selected.resourceType || '-'}</dd>
                  </div>
                  <div>
                    <dt className="text-[11px] font-bold text-soft">对象编号</dt>
                    <dd className="mt-1 break-words font-extrabold text-ink">{selected.resourceId || '-'}</dd>
                  </div>
                  <div>
                    <dt className="text-[11px] font-bold text-soft">处理人</dt>
                    <dd className="mt-1 font-extrabold text-ink">{selected.handlerName || '-'}</dd>
                  </div>
                  <div>
                    <dt className="text-[11px] font-bold text-soft">处理时间</dt>
                    <dd className="mt-1 font-extrabold text-ink">{formatDate(selected.handledAt)}</dd>
                  </div>
                </dl>

                <div>
                  <label className="text-[11px] font-bold text-soft">处理备注</label>
                  <textarea
                    value={note}
                    onChange={(event) => setNote(event.target.value)}
                    rows={4}
                    placeholder="记录处理结果、重试说明或忽略原因"
                    className="mt-1.5 w-full resize-none rounded-[4px] border border-line bg-white px-2.5 py-2 text-xs outline-none focus:border-brand"
                  />
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <button type="button" disabled={saving} onClick={() => void mutate('acknowledge')} className="inline-flex h-9 items-center justify-center gap-1.5 rounded-[4px] border border-line bg-white px-2 text-xs font-bold text-muted hover:border-brand hover:text-brand disabled:opacity-60">
                    <Eye className="h-3.5 w-3.5" />
                    标记处理中
                  </button>
                  <button type="button" disabled={saving} onClick={() => void mutate('retry')} className="inline-flex h-9 items-center justify-center gap-1.5 rounded-[4px] border border-line bg-white px-2 text-xs font-bold text-muted hover:border-brand hover:text-brand disabled:opacity-60">
                    <RotateCcw className="h-3.5 w-3.5" />
                    记录重试
                  </button>
                  <button type="button" disabled={saving} onClick={() => void mutate('resolve')} className="inline-flex h-9 items-center justify-center gap-1.5 rounded-[4px] bg-ink px-2 text-xs font-extrabold text-white disabled:opacity-60">
                    <CheckCircle2 className="h-3.5 w-3.5" />
                    标记解决
                  </button>
                  <button type="button" disabled={saving} onClick={() => void mutate('ignore')} className="inline-flex h-9 items-center justify-center gap-1.5 rounded-[4px] border border-line bg-white px-2 text-xs font-bold text-muted hover:border-red-300 hover:text-red-700 disabled:opacity-60">
                    <XCircle className="h-3.5 w-3.5" />
                    忽略
                  </button>
                </div>

                <div>
                  <div className="mb-1.5 text-[11px] font-bold text-soft">上下文</div>
                  <pre className="max-h-[230px] overflow-auto rounded-[4px] border border-line bg-white p-2.5 text-[11px] leading-5 text-muted">{stringifyPayload(selected.payload)}</pre>
                </div>
              </div>
            )}
          </aside>
        </div>
      </section>
      </div>
    </AdminShell>
  )
}
