import React from 'react';
import { Tooltip, Progress } from 'antd';
import { NodeMetric } from '../store/metricsStore';

interface Props {
    node: string;
    stats: NodeMetric;
    prevStats?: NodeMetric | null;
}

const MetricIndicator: React.FC<Props> = ({ node, stats, prevStats }) => {
    const cpu = stats.cpu_utilization ?? 0;
    const totalMemory = (stats.memory_total ?? 0) + (stats.memory_available ?? 0);
    const usedMemory = stats.memory_total ?? 0;
    const memoryPercent = totalMemory > 0 ? (usedMemory / totalMemory) * 100 : 0;

    const prevCpu = prevStats?.cpu_utilization;
    const prevTotal = (prevStats?.memory_total ?? 0) + (prevStats?.memory_available ?? 0);
    const prevUsed = prevStats?.memory_total ?? 0;
    const prevMemoryPercent = prevTotal > 0 ? (prevUsed / prevTotal) * 100 : null;

    const cpuColor = cpu > 80 ? '#ff4d4f' : '#52c41a';
    const memColor = memoryPercent > 80 ? '#ff4d4f' : '#1890ff';

    return (
        <Tooltip
            title={
                <div>
                    <div>{node}</div>
                    <div>CPU: {cpu.toFixed(1)}% {prevCpu !== undefined ? `(было ${prevCpu.toFixed(1)}%)` : ''}</div>
                    <div>
                        Память: {(usedMemory / 1048576).toFixed(0)} / {(totalMemory / 1048576).toFixed(0)} МБ ({memoryPercent.toFixed(1)}%)
                        {prevMemoryPercent !== null ? ` (было ${prevMemoryPercent.toFixed(1)}%)` : ''}
                    </div>
                </div>
            }
        >
            <div style={{ position: 'relative', width: 48, height: 48, marginRight: 12 }}>
                <Progress
                    type="circle"
                    percent={memoryPercent}
                    format={() => ''}
                    size={48}
                    strokeColor={memColor}
                    railColor="#f0f0f0"
                    strokeWidth={6}
                    style={{ position: 'absolute', top: 0, left: 0 }}
                />
                <Progress
                    type="circle"
                    percent={cpu}
                    format={() => ''}
                    size={32}
                    strokeColor={cpuColor}
                    railColor="#f0f0f0"
                    strokeWidth={6}
                    style={{ position: 'absolute', top: 8, left: 8 }}
                />
                <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', fontSize: 10, fontWeight: 600 }}>
                    {cpu.toFixed(0)}%
                </div>
            </div>
        </Tooltip>
    );
};

export default MetricIndicator;
