import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, Cell,
} from 'recharts';
import { Typography } from 'antd';
import type { ContainerResource } from '@/types/api';

const { Text } = Typography;

interface ContainerMemoryChartProps {
  containers: ContainerResource[];
  height?: number;
}

function memColor(mb: number, maxMb: number): string {
  const ratio = maxMb > 0 ? mb / maxMb : 0;
  if (ratio > 0.7) return '#ff4d4f';
  if (ratio > 0.4) return '#faad14';
  return '#52c41a';
}

export default function ContainerMemoryChart({ containers, height = 180 }: ContainerMemoryChartProps) {
  const sorted = [...containers]
    .filter(c => c.memoryMB > 0)
    .sort((a, b) => b.memoryMB - a.memoryMB);

  if (sorted.length === 0) {
    return <Text type="secondary" style={{ display: 'block', textAlign: 'center', padding: 16 }}>No container data</Text>;
  }

  const maxMem = sorted[0]?.memoryMB ?? 1;
  const chartData = sorted.map(c => ({ name: c.label, memory: c.memoryMB }));

  return (
    <ResponsiveContainer width="100%" height={height}>
      <BarChart data={chartData} layout="vertical" margin={{ top: 4, right: 16, left: 4, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" strokeOpacity={0.3} horizontal={false} />
        <XAxis type="number" tick={{ fontSize: 10 }} unit="MB" />
        <YAxis type="category" dataKey="name" tick={{ fontSize: 10 }} width={70} />
        <Tooltip formatter={(v) => `${v} MB`} contentStyle={{ fontSize: 12, borderRadius: 6 }} />
        <Bar dataKey="memory" radius={[0, 4, 4, 0]}>
          {chartData.map((entry, i) => (
            <Cell key={i} fill={memColor(entry.memory, maxMem)} />
          ))}
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );
}
