'use client'

// 2026-04-26 P2.5 by Claude — AIOps Timeline
// ============================================================
// TimelineStage — 單階段 Card
// 顯示階段圖示 / 狀態 / 時間戳 / 摘要
// 點擊展開 TimelineStageDetails
// ============================================================

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import {
  CircleAlert,
  Search,
  Brain,
  Zap,
  CheckCircle2,
  GraduationCap,
  ChevronDown,
  ChevronRight,
  Clock,
  SkipForward,
  Loader2,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { TimelineStageDetails } from './TimelineStageDetails'
import type { StageType, StageStatus, StageData } from './types'

// ----- Config -----

interface StageConfig {
  Icon: typeof CircleAlert
  accentClass: string        // border-left色
  iconBg: string             // icon 背景色
  iconColor: string          // icon 前景色
  labelKey: string
}

const STAGE_CONFIG: Record<StageType, StageConfig> = {
  alert: {
    Icon: CircleAlert,
    accentClass: 'border-l-status-critical',
    iconBg: 'bg-status-critical/10',
    iconColor: 'text-status-critical',
    labelKey: 'alert',
  },
  diagnose: {
    Icon: Search,
    accentClass: 'border-l-claw-blue',
    iconBg: 'bg-claw-blue/10',
    iconColor: 'text-claw-blue',
    labelKey: 'diagnose',
  },
  decide: {
    Icon: Brain,
    accentClass: 'border-l-status-thinking',
    iconBg: 'bg-status-thinking/10',
    iconColor: 'text-status-thinking',
    labelKey: 'decide',
  },
  execute: {
    Icon: Zap,
    accentClass: 'border-l-status-warning',
    iconBg: 'bg-status-warning/10',
    iconColor: 'text-status-warning',
    labelKey: 'execute',
  },
  verify: {
    Icon: CheckCircle2,
    accentClass: 'border-l-status-healthy',
    iconBg: 'bg-status-healthy/10',
    iconColor: 'text-status-healthy',
    labelKey: 'verify',
  },
  learn: {
    Icon: GraduationCap,
    accentClass: 'border-l-nothing-gray-400',
    iconBg: 'bg-nothing-gray-100',
    iconColor: 'text-nothing-gray-600',
    labelKey: 'learn',
  },
}

const STATUS_CONFIG: Record<StageStatus, {
  badge: string
  badgeText: string
  labelKey: string
}> = {
  success: {
    badge: 'bg-status-healthy/10 border border-status-healthy/20',
    badgeText: 'text-status-healthy',
    labelKey: 'success',
  },
  running: {
    badge: 'bg-status-syncing/10 border border-status-syncing/20',
    badgeText: 'text-status-syncing',
    labelKey: 'running',
  },
  failed: {
    badge: 'bg-status-critical/10 border border-status-critical/20',
    badgeText: 'text-status-critical',
    labelKey: 'failed',
  },
  skipped: {
    badge: 'bg-nothing-gray-100 border border-nothing-gray-200',
    badgeText: 'text-nothing-gray-400',
    labelKey: 'skipped',
  },
  pending: {
    badge: 'bg-nothing-gray-50 border border-nothing-gray-200',
    badgeText: 'text-nothing-gray-400',
    labelKey: 'pending',
  },
}

// ----- Helpers -----

function formatTs(iso: string): string {
  try {
    return new Date(iso).toLocaleTimeString('zh-TW', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false,
    })
  } catch {
    return iso
  }
}

function formatDuration(ms?: number): string | null {
  if (ms === undefined || ms === null || ms === 0) return null
  if (ms < 1000) return `${ms}ms`
  return `${(ms / 1000).toFixed(1)}s`
}

// ----- Status indicator (left-most column) -----

function StatusDot({ status }: { status: StageStatus }) {
  if (status === 'running') {
    return <Loader2 className="w-4 h-4 text-status-syncing animate-spin" />
  }
  if (status === 'skipped') {
    return <SkipForward className="w-4 h-4 text-nothing-gray-300" />
  }
  const colorMap: Record<StageStatus, string> = {
    success: 'bg-status-healthy shadow-[0_0_6px_rgba(34,197,94,0.4)]',
    failed:  'bg-status-critical shadow-[0_0_6px_rgba(255,51,0,0.4)]',
    running: 'bg-status-syncing',
    skipped: 'bg-nothing-gray-300',
    pending: 'bg-nothing-gray-200',
  }
  return (
    <div className={cn('w-3 h-3 rounded-full flex-shrink-0', colorMap[status])} />
  )
}

// ----- Main component -----

interface TimelineStageProps {
  stage: StageType
  status: StageStatus
  timestamp: string
  duration_ms?: number
  data: StageData
  /** CSS 動畫延遲（階梯式入場）*/
  animationDelay?: number
  /** 是否跳過此階段（顯示灰色） */
  isSkipped?: boolean
}

export function TimelineStage({
  stage,
  status,
  timestamp,
  duration_ms,
  data,
  animationDelay = 0,
  isSkipped = false,
}: TimelineStageProps) {
  const t = useTranslations('aiopsTimeline')
  const [expanded, setExpanded] = useState(false)

  const cfg = STAGE_CONFIG[stage]
  const stCfg = STATUS_CONFIG[status]
  const Icon = cfg.Icon
  const dur = formatDuration(duration_ms)

  const canExpand = status !== 'pending' && status !== 'skipped'

  return (
    <div
      className="animate-slide-in-up"
      style={{ animationDelay: `${animationDelay}ms`, animationFillMode: 'both' }}
    >
      {/* Card */}
      <div
        className={cn(
          'bg-white rounded-card border border-nothing-gray-200 shadow-card',
          'border-l-4 transition-all duration-200',
          cfg.accentClass,
          isSkipped && 'opacity-40',
          canExpand && 'cursor-pointer hover:shadow-card-hover hover:border-nothing-gray-300',
          expanded && 'shadow-card-hover'
        )}
        onClick={() => canExpand && setExpanded(!expanded)}
        role={canExpand ? 'button' : undefined}
        tabIndex={canExpand ? 0 : undefined}
        aria-expanded={canExpand ? expanded : undefined}
        aria-label={canExpand ? t('stage.toggle_details', { stage: t(`stages.${cfg.labelKey}`) }) : undefined}
        onKeyDown={(e) => {
          if (canExpand && (e.key === 'Enter' || e.key === ' ')) {
            e.preventDefault()
            setExpanded(!expanded)
          }
        }}
      >
        {/* Header Row */}
        <div className="flex items-center gap-3 p-3 sm:p-4">
          {/* Stage icon */}
          <div className={cn('flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center', cfg.iconBg)}>
            <Icon className={cn('w-4 h-4', cfg.iconColor)} aria-hidden="true" />
          </div>

          {/* Stage label + status */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="font-heading text-sm font-semibold text-nothing-black">
                {t(`stages.${cfg.labelKey}`)}
              </span>
              <span className={cn(
                'inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-body font-bold uppercase tracking-wider',
                stCfg.badge, stCfg.badgeText
              )}>
                {t(`status.${stCfg.labelKey}`)}
              </span>
            </div>

            {/* Timestamp + duration */}
            <div className="flex items-center gap-2 mt-0.5">
              <Clock className="w-3 h-3 text-nothing-gray-300" aria-hidden="true" />
              <span className="font-body text-[11px] text-nothing-gray-400 tabular-nums">
                {formatTs(timestamp)}
              </span>
              {dur && (
                <>
                  <span className="text-nothing-gray-200">·</span>
                  <span className="font-body text-[11px] text-nothing-gray-400 tabular-nums">
                    {dur}
                  </span>
                </>
              )}
            </div>
          </div>

          {/* Status dot + chevron */}
          <div className="flex items-center gap-2 flex-shrink-0">
            <StatusDot status={status} />
            {canExpand && (
              <div className={cn('transition-transform duration-200', expanded && 'rotate-180')}>
                <ChevronDown className="w-4 h-4 text-nothing-gray-400" />
              </div>
            )}
            {!canExpand && <ChevronRight className="w-4 h-4 text-nothing-gray-200" />}
          </div>
        </div>

        {/* Expanded details */}
        {expanded && canExpand && (
          <div className="px-3 sm:px-4 pb-4 pt-0 border-t border-nothing-gray-100">
            <div className="pt-3">
              <TimelineStageDetails stage={stage} data={data} />
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
