/**
 * TokenUsage — Token 统计面板
 *
 * 始终展示完整结构，无会话时显示零值。
 * 固定在详情面板中部，高度由内容自然决定。
 */

import { Box, Typography, Stack, Table, TableBody, TableRow, TableCell } from '@mui/material';
import { Zap } from 'lucide-react';
import { useAgentStore } from '@renderer/stores/agent-store';
import { formatTokens } from '@renderer/lib/formatters';

export function TokenUsage(): React.JSX.Element {
  const tokenUsage = useAgentStore((s) => s.tokenUsage);
  const maxIterations = useAgentStore((s) => s.maxIterations);
  const currentIteration = useAgentStore((s) => s.currentIteration);
  const contextWindow = useAgentStore((s) => s.contextWindow);

  const maxTokens = contextWindow;
  // v0.3.18 修复: 上下文占用百分比改用 lastInputTokens（单次占用），而非累计 totalTokens
  // 之前 totalTokens 是所有轮次累加值，除以单次窗口得出无意义的百分比
  const contextPercent = maxTokens > 0 && tokenUsage.lastInputTokens > 0
    ? Math.min((tokenUsage.lastInputTokens / maxTokens) * 100, 100)
    : 0;
  // 累计消耗的输入/输出占比（用于进度条展示累计消耗的构成）
  const inputPercent = tokenUsage.totalTokens > 0
    ? (tokenUsage.inputTokens / tokenUsage.totalTokens) * 100
    : 0;

  return (
    <Box sx={{ mt: 2, pt: 2, borderTop: 1, borderColor: 'divider', flexShrink: 0 }}>
      {/* 标题 */}
      <Stack direction="row" spacing={1} sx={{ mb: 1.5, alignItems: 'center' }}>
        <Zap size={14} style={{ color: '#fbbf24' }} />
        <Typography variant="caption" sx={{ fontWeight: 600, textTransform: 'uppercase', letterSpacing: 1, color: 'text.secondary' }}>
          Token 用量
        </Typography>
      </Stack>

      {/* 进度条 */}
      <Box sx={{ width: '100%', height: 6, borderRadius: 3, overflow: 'hidden', mb: 2, bgcolor: 'action.hover', display: 'flex' }}>
        <Box sx={{ height: '100%', width: `${inputPercent}%`, bgcolor: '#22d3ee', transition: 'width 300ms', borderRadius: '3px 0 0 3px' }} />
        <Box sx={{ height: '100%', width: `${Math.max(100 - inputPercent, 0)}%`, bgcolor: '#a855f7', transition: 'width 300ms', borderRadius: '0 3px 3px 0' }} />
      </Box>

      {/* 数值卡片 */}
      <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1.5, mb: 1.5 }}>
        <StatCard label="输入" value={formatTokens(tokenUsage.inputTokens)} color="#22d3ee" />
        <StatCard label="输出" value={formatTokens(tokenUsage.outputTokens)} color="#a855f7" />
      </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%' }}>累计消耗</TableCell>
            <TableCell sx={{ fontFamily: 'monospace', fontWeight: 600, color: 'text.primary', fontSize: 12, textAlign: 'right' }}>
              {tokenUsage.totalTokens > 0 ? formatTokens(tokenUsage.totalTokens) : '-'}
            </TableCell>
          </TableRow>
          <TableRow>
            <TableCell sx={{ color: 'text.secondary', fontSize: 11 }}>上下文占用</TableCell>
            <TableCell sx={{
              fontFamily: 'monospace', fontWeight: 600, fontSize: 11, textAlign: 'right',
              color: contextPercent > 80 ? 'error.main' : contextPercent > 60 ? 'warning.main' : 'text.secondary',
            }}>
              {tokenUsage.lastInputTokens > 0 ? `${formatTokens(tokenUsage.lastInputTokens)} (${contextPercent.toFixed(1)}%)` : '-'}
            </TableCell>
          </TableRow>
          {tokenUsage.lastCompressedSaved > 0 && (
            <TableRow>
              <TableCell sx={{ color: 'success.main', fontSize: 11 }}>压缩节省</TableCell>
              <TableCell sx={{ fontFamily: 'monospace', fontWeight: 600, fontSize: 11, color: 'success.main', textAlign: 'right' }}>
                {formatTokens(tokenUsage.lastCompressedSaved)}
              </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>
        </TableBody>
      </Table>
    </Box>
  );
}

function StatCard({ label, value, color }: { label: string; value: string; color: string }) {
  return (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, px: 1.5, py: 1.25, borderRadius: 1.5, bgcolor: 'action.hover' }}>
      <Box sx={{ width: 8, height: 8, borderRadius: '50%', bgcolor: color, flexShrink: 0 }} />
      <Typography variant="caption" sx={{ color: 'text.secondary', fontSize: 11 }}>{label}</Typography>
      <Typography variant="caption" sx={{ ml: 'auto', pl: 1, fontFamily: 'monospace', fontWeight: 600, color: 'text.primary', fontSize: 12 }}>{value}</Typography>
    </Box>
  );
}
