'use client'

/**
 * EventsTable — 治理事件表格
 * ===========================
 * 欄位：event_type badge / triggered_at / status / impact / expand
 * 展開行：EventDetailDrawer（inline，非側滑）
 * 分頁：底部 offset，每頁 20 筆
 *
 * @created 2026-05-02 Claude Sonnet 4.6 — governance PR 3-5
 */

import { Fragment, useState } from 'react'
import { ChevronDown, ChevronLeft, ChevronRight, AlertTriangle, ShieldCheck } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { StatusOrb } from '@/components/ui/status-orb'
import { EventDetailDrawer } from './event-detail-drawer'

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

export interface DispatchRecord {
  created_at: string
  action: string
  status: 'pending' | 'succeeded' | 'failed'
}

export interface GovernanceEvent {
  id: string
  event_type: string
  triggered_at: string
  status: 'resolved' | 'unresolved'
  severity?: 'critical' | 'warning' | 'info'
  impact_summary?: string
  raw_data?: Record<string, unknown>
  remediation?: string
  dispatch_records?: DispatchRecord[]
}

interface EventsTableProps {
  events: GovernanceEvent[]
  loading?: boolean
  error?: boolean
  onRetry?: () => void
  total: number
  page: number
  pageSize: number
  onPageChange: (page: number) => void
}

// =============================================================================
// Styles
// =============================================================================

const EVENT_TYPE_COLORS: Record<string, { bg: string; text: string }> = {
  slo_violation:        { bg: 'rgba(255,51,0,0.08)',    text: '#FF3300' },
  governance_slo_data_gap: { bg: 'rgba(255,51,0,0.08)', text: '#FF3300' },
  knowledge_degradation: { bg: 'rgba(245,158,11,0.10)', text: '#d97010' },
  kb_stale:            { bg: 'rgba(245,158,11,0.10)',  text: '#d97010' },
  execution_blast_radius: { bg: 'rgba(245,158,11,0.10)', text: '#d97010' },
  slo_breach:         { bg: 'rgba(255,51,0,0.08)',    text: '#FF3300' },
  accuracy_drop:      { bg: 'rgba(245,158,11,0.10)',  text: '#d97010' },
  km_stall:           { bg: 'rgba(74,144,217,0.10)',  text: '#2563EB' },
  mcp_failure:        { bg: 'rgba(139,92,246,0.10)',  text: '#7C3AED' },
  trust_degradation:  { bg: 'rgba(236,72,153,0.10)',  text: '#DB2777' },
}

const EVENT_TYPE_LABEL_KEYS = new Set([
  'slo_violation',
  'governance_slo_data_gap',
  'knowledge_degradation',
  'kb_stale',
  'execution_blast_radius',
  'conservative_mode',
  'replay_degraded',
  'self_demotion',
  'slo_breach',
  'accuracy_drop',
  'km_stall',
  'mcp_failure',
  'trust_degradation',
])

function getEventTypeStyle(type: string) {
  return EVENT_TYPE_COLORS[type] ?? { bg: 'rgba(135,134,127,0.10)', text: '#87867f' }
}

// =============================================================================
// Skeleton rows
// =============================================================================

function SkeletonRow() {
  return (
    <tr style={{ borderBottom: '0.5px solid #e0ddd4' }}>
      {[80, 120, 60, 180, 40].map((w, i) => (
        <td key={i} style={{ padding: '10px 12px' }}>
          <div style={{ width: w, height: 12, borderRadius: 4, background: '#e0ddd4', animation: 'pulse 1.5s infinite', animationDelay: `${i * 0.08}s` }} />
        </td>
      ))}
    </tr>
  )
}

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

export function EventsTable({
  events, loading = false, error = false, onRetry,
  total, page, pageSize, onPageChange,
}: EventsTableProps) {
  const t = useTranslations('governance.events')
  const tType = useTranslations('governance.events.eventType')
  const [expandedId, setExpandedId] = useState<string | null>(null)

  const totalPages = Math.max(1, Math.ceil(total / pageSize))

  const formatDate = (iso: string) =>
    new Date(iso).toLocaleString('zh-TW', {
      month: '2-digit', day: '2-digit',
      hour: '2-digit', minute: '2-digit',
    })

  const thStyle: React.CSSProperties = {
    fontFamily: "'DM Mono', monospace",
    fontSize: 10,
    fontWeight: 600,
    color: '#87867f',
    textTransform: 'uppercase',
    letterSpacing: '0.6px',
    padding: '8px 12px',
    textAlign: 'left',
    borderBottom: '0.5px solid #e0ddd4',
    whiteSpace: 'nowrap',
  }

  const eventTypeLabel = (eventType: string) => {
    if (!EVENT_TYPE_LABEL_KEYS.has(eventType)) return eventType
    return tType(eventType as Parameters<typeof tType>[0])
  }

  return (
    <div style={{ overflow: 'hidden' }}>
      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed' }}>
          <colgroup>
            <col style={{ width: '15%' }} />
            <col style={{ width: '18%' }} />
            <col style={{ width: '12%' }} />
            <col style={{ width: 'auto' }} />
            <col style={{ width: '52px' }} />
          </colgroup>
          <thead>
            <tr style={{ background: '#faf9f3' }}>
              <th style={thStyle}>{t('column.eventType')}</th>
              <th style={thStyle}>{t('column.triggeredAt')}</th>
              <th style={thStyle}>{t('column.status')}</th>
              <th style={thStyle}>{t('column.impact')}</th>
              <th style={{ ...thStyle, textAlign: 'center' }}>{t('column.actions')}</th>
            </tr>
          </thead>

          <tbody>
            {/* Loading state */}
            {loading && Array.from({ length: 5 }).map((_, i) => <SkeletonRow key={i} />)}

            {/* Error state */}
            {!loading && error && (
              <tr>
                <td colSpan={5}>
                  <div style={{
                    display: 'flex', flexDirection: 'column', alignItems: 'center',
                    justifyContent: 'center', padding: '40px 20px', gap: 12,
                  }}>
                    <AlertTriangle size={24} style={{ color: '#F59E0B' }} />
                    <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 12, color: '#87867f' }}>
                      {t('errorState')}
                    </span>
                    {onRetry && (
                      <button
                        onClick={onRetry}
                        style={{
                          padding: '6px 16px',
                          border: '0.5px solid #d97757',
                          borderRadius: 6,
                          background: 'transparent',
                          color: '#d97757',
                          cursor: 'pointer',
                          fontFamily: "'DM Mono', monospace",
                          fontSize: 11,
                        }}
                      >
                        {t('retry')}
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            )}

            {/* Empty state */}
            {!loading && !error && events.length === 0 && (
              <tr>
                <td colSpan={5}>
                  <div style={{
                    display: 'flex', flexDirection: 'column', alignItems: 'center',
                    justifyContent: 'center', padding: '40px 20px', gap: 12,
                  }}>
                    <div style={{
                      width: 40, height: 40, borderRadius: '50%',
                      background: '#22C55E1A',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <ShieldCheck size={20} style={{ color: '#22C55E' }} />
                    </div>
                    <div style={{ textAlign: 'center' }}>
                      <div style={{ fontFamily: 'Syne, sans-serif', fontSize: 14, fontWeight: 600, color: '#141413', marginBottom: 4 }}>
                        {t('emptyState')}
                      </div>
                      <div style={{ fontFamily: "'DM Mono', monospace", fontSize: 11, color: '#87867f' }}>
                        {t('emptyStateHint')}
                      </div>
                    </div>
                  </div>
                </td>
              </tr>
            )}

            {/* Data rows */}
            {!loading && !error && events.map(event => {
              const isExpanded = expandedId === event.id
              const typeStyle = getEventTypeStyle(event.event_type)

              return (
                <Fragment key={event.id}>
                  <tr
                    style={{
                      borderBottom: isExpanded ? 'none' : '0.5px solid #e0ddd4',
                      transition: 'background 0.12s',
                      background: isExpanded ? 'rgba(217,119,87,0.03)' : 'transparent',
                    }}
                    onMouseEnter={e => { if (!isExpanded) (e.currentTarget as HTMLElement).style.background = 'rgba(217,119,87,0.04)' }}
                    onMouseLeave={e => { if (!isExpanded) (e.currentTarget as HTMLElement).style.background = 'transparent' }}
                  >
                    {/* event_type badge */}
                    <td style={{ padding: '10px 12px' }}>
                      <span style={{
                        display: 'inline-block',
                        padding: '2px 7px',
                        borderRadius: 4,
                        background: typeStyle.bg,
                        color: typeStyle.text,
                        fontFamily: "'DM Mono', monospace",
                        fontSize: 10,
                        fontWeight: 600,
                        letterSpacing: '0.3px',
                        whiteSpace: 'nowrap',
                      }}>
                        {eventTypeLabel(event.event_type)}
                      </span>
                    </td>

                    {/* triggered_at */}
                    <td style={{ padding: '10px 12px', fontFamily: "'DM Mono', monospace", fontSize: 11, color: '#141413', whiteSpace: 'nowrap' }}>
                      {formatDate(event.triggered_at)}
                    </td>

                    {/* status */}
                    <td style={{ padding: '10px 12px' }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                        <StatusOrb
                          status={event.status === 'resolved' ? 'healthy' : 'warning'}
                          size="xs"
                          pulse={event.status === 'unresolved'}
                        />
                        <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 11, color: '#141413' }}>
                          {t(`status.${event.status}`)}
                        </span>
                      </span>
                    </td>

                    {/* impact */}
                    <td style={{
                      padding: '10px 12px',
                      fontFamily: "'DM Mono', monospace",
                      fontSize: 11,
                      color: '#87867f',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}>
                      {event.impact_summary ?? '—'}
                    </td>

                    {/* expand */}
                    <td style={{ padding: '10px 12px', textAlign: 'center' }}>
                      <button
                        onClick={() => setExpandedId(isExpanded ? null : event.id)}
                        aria-label={isExpanded ? t('collapse') : t('expand')}
                        aria-expanded={isExpanded}
                        style={{
                          background: 'none', border: 'none', cursor: 'pointer',
                          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                          padding: 4,
                          borderRadius: 4,
                          transition: 'background 0.12s',
                          color: isExpanded ? '#d97757' : '#87867f',
                        }}
                        onMouseEnter={e => (e.currentTarget.style.background = 'rgba(217,119,87,0.08)')}
                        onMouseLeave={e => (e.currentTarget.style.background = 'none')}
                      >
                        <ChevronDown
                          size={14}
                          style={{
                            transform: isExpanded ? 'rotate(180deg)' : 'none',
                            transition: 'transform 0.18s',
                          }}
                        />
                      </button>
                    </td>
                  </tr>

                  {/* Inline expand drawer */}
                  {isExpanded && <EventDetailDrawer key={`detail-${event.id}`} event={event} />}
                </Fragment>
              )
            })}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {!loading && !error && total > 0 && (
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '10px 16px',
          borderTop: '0.5px solid #e0ddd4',
          background: '#faf9f3',
        }}>
          <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, color: '#87867f' }}>
            {t('perPage')} {total}
          </span>

          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <button
              onClick={() => onPageChange(page - 1)}
              disabled={page <= 1}
              aria-label={t('prevPage')}
              style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 28, height: 28,
                border: '0.5px solid #e0ddd4',
                borderRadius: 6,
                background: '#fff',
                cursor: page <= 1 ? 'not-allowed' : 'pointer',
                opacity: page <= 1 ? 0.4 : 1,
                color: '#141413',
              }}
            >
              <ChevronLeft size={12} />
            </button>

            <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 11, color: '#141413' }}>
              {page} / {totalPages}
            </span>

            <button
              onClick={() => onPageChange(page + 1)}
              disabled={page >= totalPages}
              aria-label={t('nextPage')}
              style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 28, height: 28,
                border: '0.5px solid #e0ddd4',
                borderRadius: 6,
                background: '#fff',
                cursor: page >= totalPages ? 'not-allowed' : 'pointer',
                opacity: page >= totalPages ? 0.4 : 1,
                color: '#141413',
              }}
            >
              <ChevronRight size={12} />
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
