/**
 * AgentMonitor — Agent 状态指示器
 */

import { Box, Typography, Stack } from '@mui/material';
import { Activity, Cpu, Clock } from 'lucide-react';
import { useEffect } 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);

  // 启动时从数据库读取 maxIterations
  useEffect(() => {
    if (window.metona?.config?.get) {
      window.metona.config.get('agent.maxIterations').then((v) => {
        if (typeof v === 'number' && v > 0) setMaxIterations(v);
      }).catch(() => {});
    }
  }, [setMaxIterations]);

  // 监听配置变更
  useEffect(() => {
    const interval = setInterval(() => {
      if (window.metona?.config?.get) {
        window.metona.config.get('agent.maxIterations').then((v) => {
          if (typeof v === 'number' && v > 0) setMaxIterations(v);
        }).catch(() => {});
      }
    }, 3000);
    return () => clearInterval(interval);
  }, [setMaxIterations]);
  const StatusIcon = STATUS_ICONS[agentStatus];
  const statusColor = AGENT_STATUS_COLORS[agentStatus];
  const statusLabel = AGENT_STATUS_LABELS[agentStatus];
  const totalDuration = traceSteps.reduce((sum, s) => sum + (s.completedAt ? s.completedAt - s.startedAt : 0), 0);

  const InfoRow = ({ icon: Icon, label, value }: { icon: typeof Activity; label: string; value: string }) => (
    <Stack direction="row" alignItems="center" sx={{ gap: 1 }}>
      <Stack direction="row" spacing={0.75} alignItems="center" sx={{ color: 'text.secondary', flexShrink: 0, minWidth: 60 }}>
        <Icon size={10} /><Typography variant="caption">{label}</Typography>
      </Stack>
      <Typography variant="caption" sx={{ fontFamily: 'monospace', color: 'text.primary', flex: 1, textAlign: 'right', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{value}</Typography>
    </Stack>
  );

  return (
    <Box sx={{ mt: 2, pt: 2, borderTop: 1, borderColor: 'divider' }}>
      <Stack direction="row" spacing={1} alignItems="center" sx={{ mb: 1.5 }}>
        <Cpu size={14} style={{ color: '#818cf8' }} />
        <Typography variant="caption" sx={{ fontWeight: 600, textTransform: 'uppercase', letterSpacing: 1, color: 'text.secondary' }}>Agent 状态</Typography>
      </Stack>
      <Stack direction="row" spacing={1} alignItems="center" sx={{ px: 1.5, py: 1, borderRadius: 1.5, mb: 1, bgcolor: 'background.default' }}>
        <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>
      </Stack>
      <Stack spacing={0.75}>
        <InfoRow icon={Activity} label="Provider" value={PROVIDER_LABELS[provider] ?? provider} />
        <InfoRow icon={Cpu} label="模型" value={model} />
        <InfoRow icon={Activity} label="迭代" value={`${currentIteration} / ${maxIterations}`} />
        {totalDuration > 0 && <InfoRow icon={Clock} label="总耗时" value={formatDuration(totalDuration)} />}
      </Stack>
    </Box>
  );
}
