/**
 * TraceViewer — ReAct 迭代追踪时间轴
 *
 * 方案 A+: 按 runId 分组渲染，每轮 AI 回复一个独立 section
 * - 所有历史 run 的 steps 都可见
 * - 每个 run 视觉分离（带标题"第 N 轮"+ 状态徽标）
 * - 当前 run 高亮显示
 *
 * flex:1 撑满详情面板剩余空间，内容超出时内部滚动。
 */

import { Box, Typography, Stack, Chip } from '@mui/material';
import { Activity, MessageSquare } from 'lucide-react';
import { useEffect, useMemo, useRef } from 'react';
import { useAgentStore } from '@renderer/stores/agent-store';
import type { TraceStep as TraceStepType } from '@renderer/stores/agent-store';
import { TraceStep } from './TraceStep';

interface RunGroup {
  runId: string;
  index: number;       // 1-based 轮次序号
  steps: TraceStepType[];
  isCurrent: boolean;  // 是否为当前正在进行的 run
  isCompleted: boolean; // 是否已完成（最后一个 step 有 completedAt）
}

function groupByRun(traceSteps: TraceStepType[], currentRunId: string | null): RunGroup[] {
  const runOrder: string[] = [];
  const runMap = new Map<string, TraceStepType[]>();

  for (const step of traceSteps) {
    const rid = step.runId;
    if (!rid) continue;
    if (!runMap.has(rid)) {
      runMap.set(rid, []);
      runOrder.push(rid);
    }
    runMap.get(rid)!.push(step);
  }

  // 当前 runId 优先；若为空（idle）则取最后一个 run 作为"当前展示"
  const effectiveCurrentRunId = currentRunId ?? (runOrder.length > 0 ? runOrder[runOrder.length - 1] : null);

  return runOrder.map((rid, i) => {
    const steps = runMap.get(rid)!;
    const lastStep = steps[steps.length - 1];
    return {
      runId: rid,
      index: i + 1,
      steps,
      isCurrent: rid === effectiveCurrentRunId,
      isCompleted: Boolean(lastStep?.completedAt),
    };
  });
}

export function TraceViewer(): React.JSX.Element {
  const allTraceSteps = useAgentStore((s) => s.traceSteps);
  const agentStatus = useAgentStore((s) => s.agentStatus);
  const currentRunId = useAgentStore((s) => s.currentRunId);

  const groups = useMemo(
    () => groupByRun(allTraceSteps, currentRunId),
    [allTraceSteps, currentRunId],
  );

  const isEmpty = groups.length === 0;

  // 自动滚动到底部：traceSteps / agentStatus 变化时触发
  // throttle 80ms 避免流式事件高频触发导致滚动卡顿
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const timer = setTimeout(() => {
      const el = scrollContainerRef.current;
      if (el) el.scrollTop = el.scrollHeight;
    }, 80);
    return () => clearTimeout(timer);
  }, [allTraceSteps, agentStatus, groups.length]);

  return (
    <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden' }}>
      <Stack direction="row" spacing={1} sx={{ mb: 1.5, flexShrink: 0, alignItems: 'center' }}>
        <Activity size={14} style={{ color: '#818cf8' }} />
        <Typography variant="caption" sx={{ fontWeight: 600, textTransform: 'uppercase', letterSpacing: 1, color: 'text.secondary' }}>
          Trace Viewer
        </Typography>
        {!isEmpty && (
          <Typography variant="caption" sx={{ color: 'text.disabled', ml: 'auto' }}>
            共 {groups.length} 轮
          </Typography>
        )}
      </Stack>

      <Box ref={scrollContainerRef} sx={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 1.5, minHeight: 0 }}>
        {isEmpty ? (
          <Typography variant="caption" sx={{ textAlign: 'center', py: 2, color: 'text.disabled', flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            等待 Agent 活动...
          </Typography>
        ) : (
          groups.map((group) => (
            <Box
              key={group.runId}
              sx={{
                border: 1,
                borderColor: group.isCurrent ? 'primary.main' : 'divider',
                borderRadius: 1,
                p: 1,
                bgcolor: group.isCurrent ? 'action.hover' : 'transparent',
                opacity: group.isCurrent ? 1 : 0.85,
              }}
            >
              <Stack
                direction="row"
                spacing={1}
                sx={{ mb: 1, alignItems: 'center', flexShrink: 0 }}
              >
                <MessageSquare size={12} style={{ color: group.isCurrent ? '#818cf8' : '#9ca3af' }} />
                <Typography
                  variant="caption"
                  sx={{
                    fontWeight: 600,
                    color: group.isCurrent ? 'primary.main' : 'text.secondary',
                    letterSpacing: 0.5,
                  }}
                >
                  第 {group.index} 轮
                </Typography>
                {group.isCurrent && agentStatus !== 'idle' && (
                  <Chip
                    label="进行中"
                    size="small"
                    color="primary"
                    variant="outlined"
                    sx={{ height: 16, fontSize: 10, '& .MuiChip-label': { px: 0.5 } }}
                  />
                )}
                {group.isCompleted && !group.isCurrent && (
                  <Chip
                    label="已完成"
                    size="small"
                    variant="outlined"
                    sx={{ height: 16, fontSize: 10, '& .MuiChip-label': { px: 0.5 }, color: 'text.disabled' }}
                  />
                )}
                <Typography variant="caption" sx={{ ml: 'auto', color: 'text.disabled', fontSize: 10 }}>
                  {group.steps.length} 步
                </Typography>
              </Stack>

              <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
                {group.steps.map((step, i) => (
                  <TraceStep
                    key={step.id}
                    step={step}
                    isCurrent={group.isCurrent && i === group.steps.length - 1 && agentStatus !== 'idle'}
                  />
                ))}
              </Box>
            </Box>
          ))
        )}
      </Box>
    </Box>
  );
}
