'use client'

/**
 * Alerts Page - 告警管理
 * =======================
 * 顯示活躍 Incidents 告警列表，按嚴重度排序
 * 資料來源: GET /api/v1/incidents
 *
 * @created 2026-04-01 ogt
 */

import { AppLayout } from '@/components/layout'
import { useTranslations } from 'next-intl'
import { useIncidents } from '@/hooks/useIncidents'
import { IncidentCard } from '@/components/incident'
import { cn } from '@/lib/utils'
import { Bell, BellOff, RefreshCw, AlertTriangle, AlertCircle, Info } from 'lucide-react'

// =============================================================================
// Severity helpers
// =============================================================================

const SEVERITY_ORDER: Record<string, number> = { P0: 0, P1: 1, P2: 2, P3: 3 }

const SEVERITY_STYLE: Record<string, { bg: string; text: string; label: string }> = {
  P0: { bg: 'bg-status-critical/10', text: 'text-status-critical', label: 'CRITICAL' },
  P1: { bg: 'bg-status-warning/10',  text: 'text-status-warning',  label: 'HIGH' },
  P2: { bg: 'bg-claw-blue/10',       text: 'text-claw-blue',       label: 'MEDIUM' },
  P3: { bg: 'bg-nothing-gray-100',   text: 'text-nothing-gray-600', label: 'LOW' },
}

function SeverityBadge({ severity }: { severity: string }) {
  const style = SEVERITY_STYLE[severity] ?? SEVERITY_STYLE['P3']
  return (
    <span className={cn(
      'inline-flex items-center gap-1 px-2 py-0.5 rounded font-body text-[11px] font-bold uppercase',
      style.bg, style.text
    )}>
      {severity === 'P0' && <AlertTriangle className="w-3 h-3" />}
      {severity === 'P1' && <AlertCircle className="w-3 h-3" />}
      {(severity === 'P2' || severity === 'P3') && <Info className="w-3 h-3" />}
      {style.label} · {severity}
    </span>
  )
}

// =============================================================================
// Stat pill
// =============================================================================

function StatPill({ label, value, highlight }: { label: string; value: number; highlight?: boolean }) {
  return (
    <div className={cn(
      'flex flex-col items-center px-5 py-3 rounded-lg border',
      highlight && value > 0
        ? 'bg-status-critical/5 border-status-critical/20'
        : 'bg-white border-nothing-gray-200'
    )}>
      <span className={cn(
        'text-2xl font-bold font-body tabular-nums',
        highlight && value > 0 ? 'text-status-critical' : 'text-nothing-black'
      )}>
        {value}
      </span>
      <span className="text-[11px] font-body text-nothing-gray-500 uppercase tracking-wider mt-0.5">
        {label}
      </span>
    </div>
  )
}

// =============================================================================
// Page
// =============================================================================

export default function AlertsPage({ params }: { params: { locale: string } }) {
  const t = useTranslations()
  const tAlerts = useTranslations('alerts')

  const { incidents, isLoading, error, refresh } = useIncidents({
    pollInterval: 15000,
    enablePolling: true,
  })

  const sorted = [...(incidents ?? [])].sort(
    (a, b) => (SEVERITY_ORDER[a.severity] ?? 9) - (SEVERITY_ORDER[b.severity] ?? 9)
  )

  const p0Count = sorted.filter(i => i.severity === 'P0').length
  const p1Count = sorted.filter(i => i.severity === 'P1').length
  const p2Count = sorted.filter(i => i.severity === 'P2').length
  const p3Count = sorted.filter(i => i.severity === 'P3').length

  return (
    <AppLayout locale={params.locale}>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h2 className="font-heading text-2xl font-bold text-nothing-black flex items-center gap-2">
            <Bell className="w-6 h-6" />
            {t('nav.alerts')}
          </h2>
          <p className="mt-1 text-sm text-nothing-gray-500 font-body">
            {t('incident.activeIncidents')} · {t('alerts.autoRefresh', { seconds: 15 })}
          </p>
        </div>
        <button
          onClick={refresh}
          disabled={isLoading}
          className={cn(
            'flex items-center gap-1.5 px-3 py-1.5 rounded-lg',
            'text-xs font-body bg-nothing-gray-100 text-nothing-gray-600',
            'hover:bg-nothing-gray-200 transition-colors',
            'disabled:opacity-50 disabled:cursor-not-allowed'
          )}
        >
          <RefreshCw className={cn('w-3.5 h-3.5', isLoading && 'animate-spin')} />
          {t('common.refresh')}
        </button>
      </div>

      {/* Severity Stats */}
      <div className="grid grid-cols-4 gap-3 mb-6">
        <StatPill label={t('incident.severity.P0')} value={p0Count} highlight />
        <StatPill label={t('incident.severity.P1')} value={p1Count} />
        <StatPill label={t('incident.severity.P2')} value={p2Count} />
        <StatPill label={t('incident.severity.P3')} value={p3Count} />
      </div>

      {/* Error */}
      {error && (
        <div className="mb-4 p-4 rounded-lg bg-status-critical/10 border border-status-critical/20 flex items-center gap-2">
          <AlertCircle className="w-4 h-4 text-status-critical" />
          <span className="text-sm font-body text-status-critical">{error}</span>
        </div>
      )}

      {/* Loading skeleton */}
      {isLoading && sorted.length === 0 && (
        <div className="flex items-center justify-center py-16">
          <RefreshCw className="w-6 h-6 animate-spin text-nothing-gray-400" />
          <span className="ml-2 text-nothing-gray-400 font-body text-sm">{t('common.loading')}</span>
        </div>
      )}

      {/* Empty state */}
      {!isLoading && sorted.length === 0 && !error && (
        <div className="flex flex-col items-center justify-center py-20 text-center">
          <BellOff className="w-12 h-12 text-nothing-gray-300 mb-4" />
          <p className="font-body text-nothing-gray-500 text-sm">{t('incident.noActiveIncidents')}</p>
          <p className="font-body text-nothing-gray-400 text-xs mt-1">{t('incident.systemStable')}</p>
        </div>
      )}

      {/* Incidents grouped by severity */}
      {sorted.length > 0 && (
        <div className="space-y-6">
          {(['P0', 'P1', 'P2', 'P3'] as const).map(sev => {
            const group = sorted.filter(i => i.severity === sev)
            if (group.length === 0) return null
            return (
              <div key={sev}>
                {/* Section header */}
                <div className="flex items-center gap-3 mb-3">
                  <SeverityBadge severity={sev} />
                  <span className="text-[11px] font-body text-nothing-gray-400">
                    {tAlerts('incidentCount', { count: group.length })}
                  </span>
                  <div className="flex-1 h-px bg-nothing-gray-200" />
                </div>
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                  {group.map(incident => (
                    <IncidentCard key={incident.incident_id} incident={incident} />
                  ))}
                </div>
              </div>
            )
          })}
        </div>
      )}
    </AppLayout>
  )
}
