'use client'

/**
 * Alert Operation Log Page — 告警操作事件日誌
 * =============================================
 * Sprint 5.2: 展示 alert_operation_log 完整事件流
 *
 * Features:
 * - GET /api/v1/alert-operation-logs (分頁、篩選)
 * - GET /api/v1/alert-operation-logs/stats (24h 統計)
 * - event_type 篩選、incident_id 篩選
 * - 18 種事件類型顏色標記
 *
 * @updated 2026-04-09 Claude Opus 4.6 — i18n 全面改用 useTranslations
 */

import { useState, useEffect, useCallback, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { AppLayout } from '@/components/layout'
import { IwoooSReadOnlyBridge } from '@/components/security/iwooos-read-only-bridge'
import { cn } from '@/lib/utils'
import {
  Activity,
  ChevronLeft,
  ChevronRight,
  RefreshCw,
  Shield,
  AlertTriangle,
  CheckCircle2,
  XCircle,
  Clock,
  Zap,
  Database,
} from 'lucide-react'

// =============================================================================
// Types
// =============================================================================

interface AlertOpLog {
  id: string
  incident_id: string | null
  approval_id: string | null
  audit_log_id: string | null
  auto_repair_id: string | null
  event_type: string
  actor: string | null
  action_detail: string | null
  success: boolean | null
  error_message: string | null
  context: Record<string, unknown>
  created_at: string
}

interface LogsResponse {
  items: AlertOpLog[]
  total: number
  limit: number
  offset: number
}

interface StatsResponse {
  total: number
  since_hours: number
  by_event_type: Record<string, number>
}

// =============================================================================
// Constants
// =============================================================================

const EVENT_TYPE_STYLE: Record<string, { i18nKey: string; color: string; icon: React.ReactNode }> = {
  ALERT_RECEIVED:        { i18nKey: 'eventAlertReceived',        color: 'text-blue-400 bg-blue-900/30',    icon: <Activity className="h-3 w-3" /> },
  TELEGRAM_SENT:         { i18nKey: 'eventTelegramSent',         color: 'text-sky-400 bg-sky-900/30',      icon: <Zap className="h-3 w-3" /> },
  USER_ACTION:           { i18nKey: 'eventUserAction',           color: 'text-purple-400 bg-purple-900/30', icon: <Shield className="h-3 w-3" /> },
  AUTO_REPAIR_TRIGGERED: { i18nKey: 'eventAutoRepairTriggered',  color: 'text-yellow-400 bg-yellow-900/30', icon: <Zap className="h-3 w-3" /> },
  EXECUTION_STARTED:     { i18nKey: 'eventExecutionStarted',     color: 'text-orange-400 bg-orange-900/30', icon: <Clock className="h-3 w-3" /> },
  EXECUTION_COMPLETED:   { i18nKey: 'eventExecutionCompleted',   color: 'text-green-400 bg-green-900/30',  icon: <CheckCircle2 className="h-3 w-3" /> },
  TELEGRAM_RESULT_SENT:  { i18nKey: 'eventTelegramResultSent',   color: 'text-sky-300 bg-sky-900/20',      icon: <Zap className="h-3 w-3" /> },
  RESOLVED:              { i18nKey: 'eventResolved',             color: 'text-green-500 bg-green-900/40',  icon: <CheckCircle2 className="h-3 w-3" /> },
  SILENCED:              { i18nKey: 'eventSilenced',             color: 'text-gray-400 bg-gray-900/30',    icon: <Shield className="h-3 w-3" /> },
  ESCALATED:             { i18nKey: 'eventEscalated',            color: 'text-red-400 bg-red-900/30',      icon: <AlertTriangle className="h-3 w-3" /> },
  GUARDRAIL_BLOCKED:     { i18nKey: 'eventGuardrailBlocked',     color: 'text-red-500 bg-red-900/40',      icon: <Shield className="h-3 w-3" /> },
  PRE_FLIGHT_PASSED:     { i18nKey: 'eventPreFlightPassed',      color: 'text-green-400 bg-green-900/30',  icon: <CheckCircle2 className="h-3 w-3" /> },
  PRE_FLIGHT_FAILED:     { i18nKey: 'eventPreFlightFailed',      color: 'text-red-400 bg-red-900/30',      icon: <XCircle className="h-3 w-3" /> },
  BACKUP_TRIGGERED:      { i18nKey: 'eventBackupTriggered',      color: 'text-blue-300 bg-blue-900/20',    icon: <Database className="h-3 w-3" /> },
  BACKUP_COMPLETED:      { i18nKey: 'eventBackupCompleted',      color: 'text-green-400 bg-green-900/30',  icon: <Database className="h-3 w-3" /> },
  BACKUP_FAILED:         { i18nKey: 'eventBackupFailed',         color: 'text-red-400 bg-red-900/30',      icon: <Database className="h-3 w-3" /> },
  APPROVAL_ESCALATED:    { i18nKey: 'eventApprovalEscalated',    color: 'text-orange-400 bg-orange-900/30', icon: <AlertTriangle className="h-3 w-3" /> },
  CHANGE_APPLIED:        { i18nKey: 'eventChangeApplied',        color: 'text-teal-400 bg-teal-900/30',    icon: <CheckCircle2 className="h-3 w-3" /> },
}

const PAGE_SIZE = 50
const ALL_EVENT_TYPES = Object.keys(EVENT_TYPE_STYLE)

// =============================================================================
// Component
// =============================================================================

export default function AlertOperationLogsPage({ params }: { params: { locale: string } }) {
  const t = useTranslations('alertOpLogs')
  const [logs, setLogs] = useState<AlertOpLog[]>([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [stats, setStats] = useState<StatsResponse | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [filterEventType, setFilterEventType] = useState<string>('')
  const [filterIncidentId, setFilterIncidentId] = useState<string>('')
  const abortRef = useRef<AbortController | null>(null)

  const apiBase = process.env.NEXT_PUBLIC_API_URL ?? ''

  const getEventLabel = (et: string) => {
    const style = EVENT_TYPE_STYLE[et]
    return style ? t(style.i18nKey as any) : et
  }

  const getEventConfig = (et: string) => {
    const style = EVENT_TYPE_STYLE[et]
    return {
      label: style ? t(style.i18nKey as any) : et,
      color: style?.color ?? 'text-gray-400 bg-gray-900/30',
      icon: style?.icon ?? <Activity className="h-3 w-3" />,
    }
  }

  const fetchLogs = useCallback(async (pageNum: number, evType: string, incId: string) => {
    abortRef.current?.abort()
    abortRef.current = new AbortController()
    setLoading(true)
    setError(null)

    try {
      const params = new URLSearchParams({
        limit: String(PAGE_SIZE),
        offset: String((pageNum - 1) * PAGE_SIZE),
      })
      if (evType) params.set('event_type', evType)
      if (incId.trim()) params.set('incident_id', incId.trim())

      const res = await fetch(`${apiBase}/api/v1/alert-operation-logs?${params}`, {
        signal: abortRef.current.signal,
      })
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      const data: LogsResponse = await res.json()
      setLogs(data.items)
      setTotal(data.total)
    } catch (err) {
      if ((err as Error).name !== 'AbortError') {
        setError(t('loadError'))
      }
    } finally {
      setLoading(false)
    }
  }, [apiBase, t])

  const fetchStats = useCallback(async () => {
    try {
      const res = await fetch(`${apiBase}/api/v1/alert-operation-logs/stats`)
      if (res.ok) setStats(await res.json())
    } catch { /* non-critical */ }
  }, [apiBase])

  useEffect(() => {
    fetchLogs(page, filterEventType, filterIncidentId)
  }, [page, filterEventType, filterIncidentId, fetchLogs])

  useEffect(() => {
    fetchStats()
    return () => abortRef.current?.abort()
  }, [fetchStats])

  const totalPages = Math.ceil(total / PAGE_SIZE)

  const formatTime = (iso: string) => {
    const d = new Date(iso)
    return d.toLocaleString('zh-TW', { timeZone: 'Asia/Taipei', hour12: false })
  }

  return (
    <AppLayout locale={params.locale}>
      <div className="p-6 space-y-6 max-w-7xl mx-auto">

        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-mono font-semibold text-white">{t('title')}</h1>
            <p className="text-xs text-gray-500 mt-0.5 font-mono">{t('subtitle')}</p>
          </div>
          <button
            onClick={() => { fetchLogs(page, filterEventType, filterIncidentId); fetchStats() }}
            className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-mono text-gray-400 hover:text-white border border-gray-700 hover:border-gray-500 rounded transition-colors"
          >
            <RefreshCw className={cn('h-3 w-3', loading && 'animate-spin')} />
            {t('refresh')}
          </button>
        </div>

        <IwoooSReadOnlyBridge variant="dark" />

        {/* Stats */}
        {stats && (
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            <div className="bg-gray-900 border border-gray-800 rounded p-3">
              <div className="text-xs text-gray-500 font-mono">{t('totalEvents24h')}</div>
              <div className="text-2xl font-mono font-semibold text-white mt-1">{stats.total.toLocaleString()}</div>
            </div>
            {['ALERT_RECEIVED', 'GUARDRAIL_BLOCKED', 'AUTO_REPAIR_TRIGGERED', 'RESOLVED'].map(et => (
              <div key={et} className="bg-gray-900 border border-gray-800 rounded p-3">
                <div className="text-xs text-gray-500 font-mono">{getEventLabel(et)}</div>
                <div className="text-2xl font-mono font-semibold text-white mt-1">
                  {(stats.by_event_type[et] ?? 0).toLocaleString()}
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Filters */}
        <div className="flex gap-3 flex-wrap">
          <select
            value={filterEventType}
            onChange={e => { setFilterEventType(e.target.value); setPage(1) }}
            className="px-3 py-1.5 text-xs font-mono bg-gray-900 border border-gray-700 text-gray-300 rounded focus:border-gray-500 outline-none"
          >
            <option value="">{t('allEventTypes')}</option>
            {ALL_EVENT_TYPES.map(et => (
              <option key={et} value={et}>{getEventLabel(et)}</option>
            ))}
          </select>
          <input
            type="text"
            placeholder={t('incidentIdFilter')}
            value={filterIncidentId}
            onChange={e => { setFilterIncidentId(e.target.value); setPage(1) }}
            className="px-3 py-1.5 text-xs font-mono bg-gray-900 border border-gray-700 text-gray-300 rounded focus:border-gray-500 outline-none w-52"
          />
          <span className="text-xs font-mono text-gray-500 self-center">
            {t('totalCount', { count: total.toLocaleString() })}
          </span>
        </div>

        {/* Error */}
        {error && (
          <div className="flex items-center gap-2 text-red-400 text-xs font-mono">
            <XCircle className="h-4 w-4" />{error}
          </div>
        )}

        {/* Table */}
        <div className="bg-gray-900 border border-gray-800 rounded overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-xs font-mono">
              <thead>
                <tr className="border-b border-gray-800 text-gray-500">
                  <th className="text-left px-4 py-2.5">{t('colTime')}</th>
                  <th className="text-left px-4 py-2.5">{t('colEventType')}</th>
                  <th className="text-left px-4 py-2.5">{t('colIncident')}</th>
                  <th className="text-left px-4 py-2.5">{t('colActor')}</th>
                  <th className="text-left px-4 py-2.5">{t('colDetail')}</th>
                  <th className="text-left px-4 py-2.5">{t('colResult')}</th>
                </tr>
              </thead>
              <tbody>
                {loading && (
                  <tr><td colSpan={6} className="text-center py-8 text-gray-600">{t('loading')}</td></tr>
                )}
                {!loading && logs.length === 0 && (
                  <tr><td colSpan={6} className="text-center py-8 text-gray-600">{t('noRecords')}</td></tr>
                )}
                {!loading && logs.map(log => {
                  const cfg = getEventConfig(log.event_type)
                  return (
                    <tr key={log.id} className="border-b border-gray-800/50 hover:bg-gray-800/30 transition-colors">
                      <td className="px-4 py-2.5 text-gray-400 whitespace-nowrap">
                        {formatTime(log.created_at)}
                      </td>
                      <td className="px-4 py-2.5">
                        <span className={cn('inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs', cfg.color)}>
                          {cfg.icon}
                          {cfg.label}
                        </span>
                      </td>
                      <td className="px-4 py-2.5 text-gray-400">
                        {log.incident_id ? (
                          <span className="text-blue-400">{log.incident_id.slice(-8)}</span>
                        ) : (
                          <span className="text-gray-700">—</span>
                        )}
                      </td>
                      <td className="px-4 py-2.5 text-gray-400">{log.actor ?? '—'}</td>
                      <td className="px-4 py-2.5 text-gray-300 max-w-xs truncate">
                        {log.action_detail ?? '—'}
                      </td>
                      <td className="px-4 py-2.5">
                        {log.success === true && <CheckCircle2 className="h-3.5 w-3.5 text-green-500" />}
                        {log.success === false && <XCircle className="h-3.5 w-3.5 text-red-500" />}
                        {log.success === null && <span className="text-gray-700">—</span>}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between text-xs font-mono text-gray-500">
            <span>{t('pageInfo', { page, total: totalPages })}</span>
            <div className="flex gap-2">
              <button
                disabled={page <= 1}
                onClick={() => setPage(p => p - 1)}
                className="flex items-center gap-1 px-3 py-1.5 border border-gray-700 rounded disabled:opacity-30 hover:border-gray-500 transition-colors"
              >
                <ChevronLeft className="h-3 w-3" />{t('prevPage')}
              </button>
              <button
                disabled={page >= totalPages}
                onClick={() => setPage(p => p + 1)}
                className="flex items-center gap-1 px-3 py-1.5 border border-gray-700 rounded disabled:opacity-30 hover:border-gray-500 transition-colors"
              >
                {t('nextPage')}<ChevronRight className="h-3 w-3" />
              </button>
            </div>
          </div>
        )}
      </div>
    </AppLayout>
  )
}
