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 RequestTrafficChartProps {
  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 RequestTrafficChart({ data, height = 200 }: RequestTrafficChartProps) {
  const series2xx = data.request_rate_2xx;
  const series4xx = data.request_rate_4xx;
  const series5xx = data.request_rate_5xx;

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

  const chartData = series2xx.timestamps.map((ts, i) => ({
    time: formatTime(ts),
    '2xx': series2xx.values[i] || 0,
    '4xx': series4xx?.values[i] || 0,
    '5xx': series5xx?.values[i] || 0,
  }));

  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 }} />
        <Tooltip contentStyle={{ fontSize: 12, borderRadius: 6 }} />
        <Legend wrapperStyle={{ fontSize: 11 }} />
        <Area type="monotone" dataKey="2xx" stackId="1" stroke="#52c41a" fill="#52c41a" fillOpacity={0.6} />
        <Area type="monotone" dataKey="4xx" stackId="1" stroke="#faad14" fill="#faad14" fillOpacity={0.6} />
        <Area type="monotone" dataKey="5xx" stackId="1" stroke="#ff4d4f" fill="#ff4d4f" fillOpacity={0.6} />
      </AreaChart>
    </ResponsiveContainer>
  );
}
