import { useEffect, useState } from 'react';
import { LineChart, Line, BarChart, Bar, AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';

type Point = { date: string; value: number };

export function ChartWidget({ metric, title, type = 'line', interval = 'day' }: {
    metric: string; title?: string; type?: 'line' | 'bar' | 'area'; interval?: string;
}) {
    const [points, setPoints] = useState<Point[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetch(`/api/metric-series/${metric}?interval=${interval}&buckets=30`, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then((r) => r.json())
            .then((d) => setPoints(d.points ?? []))
            .catch(() => setPoints([]))
            .finally(() => setLoading(false));
    }, [metric, interval]);

    return (
        <div className="rounded-xl border border-border bg-card p-5 shadow-sm">
            {title && <p className="mb-3 text-sm font-medium text-foreground">{title}</p>}
            {loading ? (
                <div className="flex h-40 items-center justify-center text-sm text-muted-foreground">Loading…</div>
            ) : points.length === 0 ? (
                <div className="flex h-40 items-center justify-center text-sm text-muted-foreground">No data yet</div>
            ) : (
                <ResponsiveContainer width="100%" height={180}>
                    {type === 'bar' ? (
                        <BarChart data={points}>
                            <XAxis dataKey="date" tick={{ fontSize: 10 }} hide={points.length > 15} />
                            <YAxis tick={{ fontSize: 10 }} width={40} />
                            <Tooltip />
                            <Bar dataKey="value" fill="var(--primary)" radius={[3, 3, 0, 0]} />
                        </BarChart>
                    ) : type === 'area' ? (
                        <AreaChart data={points}>
                            <XAxis dataKey="date" tick={{ fontSize: 10 }} hide={points.length > 15} />
                            <YAxis tick={{ fontSize: 10 }} width={40} />
                            <Tooltip />
                            <Area dataKey="value" stroke="var(--primary)" fill="var(--primary)" fillOpacity={0.15} />
                        </AreaChart>
                    ) : (
                        <LineChart data={points}>
                            <XAxis dataKey="date" tick={{ fontSize: 10 }} hide={points.length > 15} />
                            <YAxis tick={{ fontSize: 10 }} width={40} />
                            <Tooltip />
                            <Line dataKey="value" stroke="var(--primary)" strokeWidth={2} dot={false} />
                        </LineChart>
                    )}
                </ResponsiveContainer>
            )}
        </div>
    );
}
