/**
 * AgentMonitor — Agent 状态指示器
 *
 * 完全使用 MUI 组件，Table 布局标签-值对。
 */

import { Box, Typography, Stack, Table, TableBody, TableRow, TableCell, Chip } from '@mui/material';
import { Activity, Cpu } from 'lucide-react';
import { useEffect, useMemo } from 'react';
import { useAgentStore, type AgentStatus } from '@renderer/stores/agent-store';
import { AGENT_STATUS_COLORS, AGENT_STATUS_LABELS, PROVIDER_LABELS } from '@renderer/lib/constants';
import { formatDuration } from '@renderer/lib/formatters';

const STATUS_ICONS: Record<AgentStatus, typeof Activity> = { idle: Activity, thinking: Cpu, executing: Cpu, error: Activity };

export function AgentMonitor(): React.JSX.Element {
  const agentStatus = useAgentStore((s) => s.agentStatus);
  const provider = useAgentStore((s) => s.provider);
  const model = useAgentStore((s) => s.model);
  const currentIteration = useAgentStore((s) => s.currentIteration);
  const maxIterations = useAgentStore((s) => s.maxIterations);
  const traceSteps = useAgentStore((s) => s.traceSteps);
  const setMaxIterations = useAgentStore((s) => s.setMaxIterations);

  useEffect(() => {
    // M-11/M-28 修复: 添加 cancelled 标志 + 错误日志记录
    let cancelled = false;
    if (window.metona?.config?.get) {
      window.metona.config.get('agent.maxIterations').then((v) => {
        if (cancelled) return;
        if (typeof v === 'number' && v > 0) setMaxIterations(v);
      }).catch((err) => {
        // M-11 修复: 记录错误而非静默吞掉，便于诊断配置加载异常
        console.error('[AgentMonitor] Failed to load maxIterations:', err);
      });
    }
    return () => { cancelled = true; };
  }, [setMaxIterations]);

  // L-14 修复: 使用 useMemo 缓存 totalDuration，避免每次渲染都遍历 traceSteps 数组
  const totalDuration = useMemo(
    () => traceSteps.reduce((sum, s) => sum + (s.completedAt ? s.completedAt - s.startedAt : 0), 0),
    [traceSteps],
  );

  const StatusIcon = STATUS_ICONS[agentStatus];
  const statusColor = AGENT_STATUS_COLORS[agentStatus];
  const statusLabel = AGENT_STATUS_LABELS[agentStatus];

  return (
    <Box sx={{ mt: 2, pt: 2, borderTop: 1, borderColor: 'divider', flexShrink: 0 }}>
      <Stack direction="row" spacing={1} sx={{ mb: 1.5, alignItems: 'center' }}>
        <Cpu size={14} style={{ color: '#818cf8' }} />
        <Typography variant="caption" sx={{ fontWeight: 600, textTransform: 'uppercase', letterSpacing: 1, color: 'text.secondary' }}>
          Agent 状态
        </Typography>
      </Stack>

      {/* 状态指示 */}
      <Box sx={{ px: 1.5, py: 1, borderRadius: 1.5, mb: 1.5, bgcolor: 'background.default', border: '1px solid', borderColor: 'divider' }}>
        <Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
          <StatusIcon
            size={14}
            style={{
              color: statusColor,
              animation: (agentStatus === 'thinking' || agentStatus === 'executing') ? 'pulse 2s infinite' : 'none',
            }}
          />
          <Typography variant="caption" sx={{ fontWeight: 500, color: statusColor }}>{statusLabel}</Typography>
          {(agentStatus === 'thinking' || agentStatus === 'executing') && (
            <Box sx={{ width: 6, height: 6, borderRadius: '50%', bgcolor: statusColor, animation: 'pulse 1.5s infinite', ml: 'auto' }} />
          )}
        </Stack>
      </Box>

      {/* 详情表格 */}
      <Table size="small" sx={{ '& .MuiTableCell-root': { border: 0, py: 0.5, px: 0.5 } }}>
        <TableBody>
          <TableRow>
            <TableCell sx={{ color: 'text.secondary', fontSize: 11, width: '40%' }}>Provider</TableCell>
            <TableCell sx={{ fontFamily: 'monospace', fontWeight: 600, fontSize: 11, color: 'text.primary', textAlign: 'right', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 0 }}>
              {PROVIDER_LABELS[provider] ?? provider}
            </TableCell>
          </TableRow>
          <TableRow>
            <TableCell sx={{ color: 'text.secondary', fontSize: 11 }}>模型</TableCell>
            <TableCell sx={{ fontFamily: 'monospace', fontWeight: 600, fontSize: 11, color: 'text.primary', textAlign: 'right', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 0 }}>
              {model}
            </TableCell>
          </TableRow>
          <TableRow>
            <TableCell sx={{ color: 'text.secondary', fontSize: 11 }}>迭代</TableCell>
            <TableCell sx={{ fontFamily: 'monospace', fontWeight: 600, fontSize: 11, color: 'text.secondary', textAlign: 'right' }}>
              {currentIteration} / {maxIterations}
            </TableCell>
          </TableRow>
          {totalDuration > 0 && (
            <TableRow>
              <TableCell sx={{ color: 'text.secondary', fontSize: 11 }}>总耗时</TableCell>
              <TableCell sx={{ fontFamily: 'monospace', fontWeight: 600, fontSize: 11, color: 'text.secondary', textAlign: 'right' }}>
                {formatDuration(totalDuration)}
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </Box>
  );
}
