import { useEffect, useMemo, useState } from 'react'
import { Activity, Brain, CircleAlert, Loader2 } from 'lucide-react'
import { FilesDownloadBox, ToolCallLine, ToolResultLine } from './AgentEventLine.jsx'
import { runtimeTimelineStatusLabel } from '../services/runtimeTimeline.js'

function elapsedLabel(timeline, now) {
  const heartbeatMs = Number(timeline?.elapsedMs || 0)
  const startedMs = Date.parse(timeline?.startedAt || '')
  const liveMs = Number.isFinite(startedMs) ? Math.max(0, now - startedMs) : 0
  const seconds = Math.floor(Math.max(heartbeatMs, liveMs) / 1000)
  if (seconds < 60) return `${seconds} 秒`
  return `${Math.floor(seconds / 60)} 分 ${seconds % 60} 秒`
}

export default function RuntimeTimeline({ timeline, isRunning = false, sessionId = '', onPreview }) {
  const [now, setNow] = useState(Date.now())
  useEffect(() => {
    if (!isRunning) return undefined
    const timer = window.setInterval(() => setNow(Date.now()), 1000)
    return () => window.clearInterval(timer)
  }, [isRunning])

  const visibleEntries = useMemo(() => (
    (timeline?.entries || []).filter(entry => entry.type !== 'assistant' && entry.type !== 'status' && entry.type !== 'artifact')
  ), [timeline?.entries])
  const files = useMemo(() => (
    (timeline?.artifacts || []).map(artifact => artifact.path || artifact.name).filter(Boolean)
  ), [timeline?.artifacts])
  const activeSessionId = timeline?.sessionId || timeline?.artifacts?.find(item => item.sessionId)?.sessionId || sessionId
  const hasActivity = isRunning || timeline?.status || visibleEntries.length > 0 || files.length > 0
  if (!hasActivity) return null

  return (
    <section className="rounded-xl border border-sky-100 bg-sky-50/40 px-3 py-2.5" aria-label="运行时实时进度">
      <div className="flex items-center gap-2 text-[12px] text-sky-800">
        {isRunning ? <Loader2 size={14} className="animate-spin" /> : <Activity size={14} />}
        <span className="font-medium">{runtimeTimelineStatusLabel(timeline, isRunning)}</span>
        <span className="ml-auto tabular-nums text-[11px] text-sky-600">{elapsedLabel(timeline, now)}</span>
      </div>

      {visibleEntries.length > 0 && (
        <div className="mt-2 space-y-1.5">
          {visibleEntries.map((entry, index) => {
            const key = `${entry.event?.eventId || entry.event?.providerEventId || 'local'}_${index}`
            if (entry.type === 'reasoning') {
              return (
                <div key={key} className="flex items-start gap-2 rounded-md border border-violet-100 bg-violet-50 px-2.5 py-2 text-[12px] text-violet-800">
                  <Brain size={13} className="mt-0.5 flex-shrink-0" />
                  <div><span className="font-medium">推理摘要：</span><span className="whitespace-pre-wrap break-words">{entry.content}</span></div>
                </div>
              )
            }
            if (entry.type === 'tool_call') return <ToolCallLine key={key} name={entry.name} args={entry.args} />
            if (entry.type === 'tool_result') return <ToolResultLine key={key} name={entry.name} result={entry.result} sessionId={activeSessionId} onPreview={onPreview} />
            if (entry.type === 'warning' || entry.type === 'error') {
              return (
                <div key={key} className="flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-2.5 py-2 text-[12px] text-amber-800">
                  <CircleAlert size={13} className="mt-0.5 flex-shrink-0" />
                  <span className="whitespace-pre-wrap break-words">{entry.content}</span>
                </div>
              )
            }
            return null
          })}
        </div>
      )}

      {files.length > 0 && (
        <div className="mt-2">
          <FilesDownloadBox sessionId={activeSessionId} files={files} onPreview={onPreview} />
        </div>
      )}
    </section>
  )
}
