'use client'

/**
 * ActionTimeline - 行動日誌時間軸 (Phase 4 企業級)
 * =================================================
 * MVP 最終閉環 - Nothing.tech 骨架風格
 *
 * 視覺鐵律：
 * - 極細灰色連接線
 * - 透明背景
 * - VT323 點陣字體
 * - 微光色彩點綴 (非大面積發光)
 */

import { useTimelineEvents, useNewestExecEventId, type TimelineEvent, type TimelineEventType, type TimelineEventStatus } from '@/stores/timeline.store'
import { cn } from '@/lib/utils'
import {
  Radio,        // SYSTEM
  Brain,        // AGENT
  ShieldAlert,  // SECURITY
  UserCheck,    // HUMAN
  Zap,          // EXEC
} from 'lucide-react'

// =============================================================================
// Event Config (統帥規格)
// =============================================================================

interface EventConfig {
  icon: React.ComponentType<{ className?: string }>
  label: string
  labelColor: string
}

const EVENT_CONFIG: Record<TimelineEventType, EventConfig> = {
  system: {
    icon: Radio,
    label: 'SYSTEM',
    labelColor: 'text-nothing-gray-500',
  },
  agent: {
    icon: Brain,
    label: 'AGENT',
    labelColor: 'text-claw-blue',
  },
  security: {
    icon: ShieldAlert,
    label: 'SECURITY',
    labelColor: 'text-status-critical',
  },
  human: {
    icon: UserCheck,
    label: 'HUMAN',
    labelColor: 'text-status-healthy',
  },
  exec: {
    icon: Zap,
    label: 'EXEC',
    labelColor: 'text-status-warning',
  },
}

const STATUS_DOT_COLOR: Record<TimelineEventStatus, string> = {
  info: 'bg-nothing-gray-400',
  success: 'bg-status-healthy',
  warning: 'bg-status-warning',
  error: 'bg-status-critical',
}

// =============================================================================
// Helper Functions
// =============================================================================

function formatTimestamp(date: Date): string {
  return date.toLocaleTimeString('zh-TW', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
  })
}

// =============================================================================
// Timeline Event Item (Nothing.tech 骨架風格)
// =============================================================================

interface TimelineItemProps {
  event: TimelineEvent
  isLast: boolean
  isNewest?: boolean
  isPulsingExec?: boolean
}

function TimelineItem({ event, isLast, isNewest = false, isPulsingExec = false }: TimelineItemProps) {
  const config = EVENT_CONFIG[event.type]
  const Icon = config.icon
  const dotColor = STATUS_DOT_COLOR[event.status]

  // 閃爍條件: 是最新項目 OR 是新發現的 EXEC 事件
  const shouldPulse = isNewest || isPulsingExec

  return (
    <div className={cn(
      "relative flex gap-3 pb-3 last:pb-0",
      shouldPulse && "animate-pulse-3s"
    )}>
      {/* Vertical Line (極細灰色) */}
      {!isLast && (
        <div className="absolute left-[5px] top-3 bottom-0 w-px bg-nothing-gray-200/60" />
      )}

      {/* Dot (微光點綴) */}
      <div className="relative z-10 flex-shrink-0 mt-0.5">
        <div className={cn(
          'w-[11px] h-[11px] rounded-full',
          dotColor,
          event.status === 'error' && 'shadow-[0_0_6px_rgba(239,68,68,0.4)]',
          event.status === 'success' && 'shadow-[0_0_6px_rgba(34,197,94,0.4)]',
        )} />
      </div>

      {/* Content */}
      <div className="flex-1 min-w-0 -mt-0.5">
        {/* Header: Timestamp + Label */}
        <div className="flex items-center gap-2 mb-0.5">
          <span className="font-dot-matrix text-[10px] text-nothing-gray-400 tracking-wider tabular-nums">
            {formatTimestamp(event.timestamp)}
          </span>
          <span className={cn(
            'font-dot-matrix text-[9px] tracking-widest',
            config.labelColor
          )}>
            [{config.label}]
          </span>
        </div>

        {/* Title */}
        <p className="font-mono text-[11px] text-nothing-gray-700 leading-tight">
          {event.title}
        </p>

        {/* Error Description - Nothing.tech 點陣紅驚嘆號 */}
        {event.status === 'error' && event.description && (
          <div className="mt-1.5 flex items-start gap-1.5 p-2 rounded bg-nothing-red/5 border border-nothing-red/20">
            <span className="font-dot-matrix text-nothing-red text-[14px] leading-none animate-pulse">!</span>
            <pre className="font-mono text-[9px] text-nothing-red/90 leading-relaxed whitespace-pre-wrap break-all">
              {event.description}
            </pre>
          </div>
        )}

        {/* Actor (if present) */}
        {event.actor && (
          <div className="flex items-center gap-1.5 mt-0.5">
            <Icon className={cn('w-2.5 h-2.5', config.labelColor)} />
            <span className="font-mono text-[9px] text-nothing-gray-500">
              {event.actor}
            </span>
            {event.actorRole && (
              <span className={cn(
                'px-1 py-0.5 rounded text-[7px] font-mono font-bold uppercase',
                event.actorRole === 'cto' || event.actorRole === 'ciso'
                  ? 'bg-status-healthy/10 text-status-healthy'
                  : event.actorRole === 'ai'
                    ? 'bg-claw-blue/10 text-claw-blue'
                    : 'bg-nothing-gray-100 text-nothing-gray-500'
              )}>
                {event.actorRole}
              </span>
            )}
          </div>
        )}

        {/* Risk Badge */}
        {event.riskLevel === 'critical' && (
          <span className="inline-block mt-1 px-1 py-0.5 rounded text-[7px] font-mono font-bold uppercase bg-status-critical/10 text-status-critical">
            CRITICAL
          </span>
        )}
      </div>
    </div>
  )
}

// =============================================================================
// Main Component
// =============================================================================

interface ActionTimelineProps {
  className?: string
  maxDisplay?: number
}

export function ActionTimeline({ className, maxDisplay = 12 }: ActionTimelineProps) {
  const events = useTimelineEvents()
  const newestExecEventId = useNewestExecEventId()
  const displayEvents = events.slice(0, maxDisplay)

  return (
    <div className={cn('', className)}>
      {/* Header (VT323 點陣風格) */}
      <div className="flex items-center justify-between mb-3 pb-2 border-b border-nothing-gray-100">
        <h3 className="font-dot-matrix text-xs text-nothing-gray-600 tracking-widest">
          ACTION LOG
        </h3>
        <span className="font-dot-matrix text-[9px] text-nothing-gray-400 tabular-nums">
          {events.length}
        </span>
      </div>

      {/* Timeline (透明背景) */}
      {displayEvents.length === 0 ? (
        <div className="py-8 text-center">
          <Radio className="w-5 h-5 text-nothing-gray-300 mx-auto mb-2" />
          <p className="font-dot-matrix text-[10px] text-nothing-gray-400 tracking-wider">
            AWAITING EVENTS...
          </p>
        </div>
      ) : (
        <div className="space-y-0">
          {displayEvents.map((event, index) => (
            <TimelineItem
              key={event.id}
              event={event}
              isLast={index === displayEvents.length - 1}
              isNewest={index === 0}
              isPulsingExec={event.id === newestExecEventId}
            />
          ))}
        </div>
      )}

      {/* More indicator */}
      {events.length > maxDisplay && (
        <div className="mt-2 pt-2 border-t border-nothing-gray-100">
          <p className="font-dot-matrix text-[9px] text-nothing-gray-400 text-center tracking-wider">
            +{events.length - maxDisplay} MORE
          </p>
        </div>
      )}
    </div>
  )
}

export default ActionTimeline
