/**
 * StatusBar — 底部状态栏
 *
 * 完全使用 MUI 组件：Table 展示状态/Provider/Token，右侧设置按钮。
 */

import { useState, useEffect } from 'react';
import { Box, Typography, IconButton, Tooltip, Table, TableBody, TableRow, TableCell } from '@mui/material';
import { Settings } from 'lucide-react';
import { useAgentStore } from '@renderer/stores/agent-store';
import { useUIStore } from '@renderer/stores/ui-store';
import { AGENT_STATUS_COLORS, AGENT_STATUS_LABELS, PROVIDER_LABELS } from '@renderer/lib/constants';
import { formatTokens } from '@renderer/lib/formatters';

export function StatusBar(): React.JSX.Element {
  const agentStatus = useAgentStore((s) => s.agentStatus);
  const provider = useAgentStore((s) => s.provider);
  const model = useAgentStore((s) => s.model);
  const tokenUsage = useAgentStore((s) => s.tokenUsage);
  const openSettings = useUIStore((s) => s.openSettings);
  const [version, setVersion] = useState('v0.1.1');

  useEffect(() => {
    // M-28 修复: 添加 cancelled 标志防止组件卸载后 setState
    let cancelled = false;
    if (window.metona?.app?.getVersion) {
      window.metona.app.getVersion().then((v) => {
        if (!cancelled) setVersion(`v${v}`);
      }).catch((err) => { console.error('[StatusBar]', err); });
    }
    return () => { cancelled = true; };
  }, []);

  return (
    <Box
      component="footer"
      sx={{
        flexShrink: 0, display: 'flex', alignItems: 'center',
        px: 2, height: 36, bgcolor: 'background.paper',
        borderTop: 1, borderColor: 'divider', userSelect: 'none',
      }}
    >
      {/* 左侧：状态信息表格 */}
      <Table size="small" sx={{
        flex: 1, width: 'auto',
        '& .MuiTableCell-root': { border: 0, py: 0, px: 1, fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap' },
      }}>
        <TableBody>
          <TableRow>
            <TableCell sx={{ width: 'auto', py: 0, px: 1 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
                <Box
                  sx={{
                    width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
                    bgcolor: AGENT_STATUS_COLORS[agentStatus],
                    animation: (agentStatus === 'thinking' || agentStatus === 'executing') ? 'pulse 2s infinite' : 'none',
                  }}
                />
                <Typography variant="caption" sx={{ color: 'text.secondary', fontSize: 11, fontWeight: 600, lineHeight: 1 }}>
                  {AGENT_STATUS_LABELS[agentStatus]}
                </Typography>
              </Box>
            </TableCell>
            <TableCell sx={{ color: 'divider', width: 1, p: 0 }}>|</TableCell>
            <TableCell sx={{ color: 'text.secondary', fontSize: 11 }}>
              {PROVIDER_LABELS[provider] ?? provider} {model}
            </TableCell>
            {tokenUsage.totalTokens > 0 && (
              <>
                <TableCell sx={{ color: 'divider', width: 1, p: 0 }}>|</TableCell>
                <TableCell sx={{ fontFamily: 'monospace', color: 'text.secondary', fontSize: 10 }}>
                  {formatTokens(tokenUsage.inputTokens)}↓ {formatTokens(tokenUsage.outputTokens)}↑
                </TableCell>
              </>
            )}
          </TableRow>
        </TableBody>
      </Table>

      {/* 右侧：版本 + 设置 */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, flexShrink: 0 }}>
        <Typography variant="caption" sx={{ color: 'text.disabled', fontSize: 10 }}>{version}</Typography>
        <Tooltip title="设置 (Ctrl+,)">
          <IconButton size="small" onClick={openSettings} sx={{ color: 'text.secondary', width: 28, height: 28 }}>
            <Settings size={14} />
          </IconButton>
        </Tooltip>
      </Box>
    </Box>
  );
}
