import {
  AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
  Legend, ResponsiveContainer,
} from 'recharts';
import { Typography } from 'antd';
import type { TimeSeriesResult } from '@/types/api';

const { Text } = Typography;

interface LatencyBandsChartProps {
  data: TimeSeriesResult;
  height?: number;
}

function formatTime(ts: number): string {
  const d = new Date(ts * 1000);
  return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

export default function LatencyBandsChart({ data, height = 200 }: LatencyBandsChartProps) {
  const p50 = data.latency_p50;
  const p95 = data.latency_p95;
  const p99 = data.latency_p99;

  if (!p50?.timestamps?.length) {
    return <Text type="secondary" style={{ display: 'block', textAlign: 'center', padding: 24 }}>No latency data</Text>;
  }

  const chartData = p50.timestamps.map((ts, i) => ({
    time: formatTime(ts),
    p50: Math.round((p50.values[i] || 0) * 1000),
    p95: Math.round((p95?.values[i] || 0) * 1000),
    p99: Math.round((p99?.values[i] || 0) * 1000),
  }));

  return (
    <ResponsiveContainer width="100%" height={height}>
      <AreaChart data={chartData} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" strokeOpacity={0.3} />
        <XAxis dataKey="time" tick={{ fontSize: 10 }} interval="preserveStartEnd" />
        <YAxis tick={{ fontSize: 10 }} unit="ms" />
        <Tooltip contentStyle={{ fontSize: 12, borderRadius: 6 }} formatter={(v) => `${v}ms`} />
        <Legend wrapperStyle={{ fontSize: 11 }} />
        <Area type="monotone" dataKey="p99" stroke="#ff4d4f" fill="#ff4d4f" fillOpacity={0.15} />
        <Area type="monotone" dataKey="p95" stroke="#faad14" fill="#faad14" fillOpacity={0.25} />
        <Area type="monotone" dataKey="p50" stroke="#52c41a" fill="#52c41a" fillOpacity={0.4} />
      </AreaChart>
    </ResponsiveContainer>
  );
}
