import React, { useState, useEffect } from 'react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';

/**
 * Resource Monitor with Live Charts
 * Replaces static CPU/RAM boxes with real-time visualization
 */

interface ResourceData {
    time: string;
    cpu: number;
    ram_percent: number;
}

export default function ResourceMonitor() {
    const [historyData, setHistoryData] = useState<ResourceData[]>([]);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        // Fetch initial data
        fetchPoolStats();

        // Poll every 2 seconds
        const interval = setInterval(fetchPoolStats, 2000);

        return () => clearInterval(interval);
    }, []);

    async function fetchPoolStats() {
        try {
            const token = localStorage.getItem('godToken') || '';
            const res = await fetch('/api/god/pool/stats', {
                headers: { 'X-God-Token': token }
            });

            if (!res.ok) return;

            const data = await res.json();

            // Mock CPU/RAM data (replace with real metrics when available)
            const newDataPoint: ResourceData = {
                time: new Date().toISOString(),
                cpu: data.pool.saturation_pct / 2, // Estimate CPU from pool saturation
                ram_percent: data.pool.saturation_pct
            };

            setHistoryData(prev => {
                const updated = [...prev, newDataPoint];
                // Keep last 60 points (2 minutes of history)
                return updated.slice(-60);
            });

            setIsLoading(false);

        } catch (error) {
            console.error('Failed to fetch pool stats:', error);
        }
    }

    if (isLoading) {
        return (
            <Card className="col-span-2 bg-slate-900 border-slate-800">
                <CardContent className="p-8 text-center text-slate-500">
                    Loading resource data...
                </CardContent>
            </Card>
        );
    }

    const latestData = historyData[historyData.length - 1];

    return (
        <Card className="col-span-2 bg-slate-900 border-slate-800">
            <CardHeader>
                <CardTitle className="flex justify-between items-center">
                    <span>Resource Load History</span>
                    <div className="flex gap-4 text-sm font-normal">
                        <span className="flex items-center gap-2">
                            <div className="w-3 h-3 rounded-full" style={{ backgroundColor: 'hsl(220 100% 50%)' }}></div>
                            CPU: {latestData?.cpu.toFixed(1)}%
                        </span>
                        <span className="flex items-center gap-2">
                            <div className="w-3 h-3 rounded-full" style={{ backgroundColor: 'hsl(270 100% 50%)' }}></div>
                            RAM: {latestData?.ram_percent.toFixed(1)}%
                        </span>
                    </div>
                </CardTitle>
            </CardHeader>
            <CardContent className="h-[250px] p-2">
                <ResponsiveContainer width="100%" height="100%">
                    <AreaChart data={historyData} margin={{ top: 10, right: 0, left: -20, bottom: 0 }}>
                        {/* Dark Mode Grid */}
                        <CartesianGrid stroke="hsl(var(--muted))" strokeDasharray="3 3" opacity={0.5} />

                        {/* X-Axis (Time) */}
                        <XAxis
                            dataKey="time"
                            tickFormatter={(t) => new Date(t).toLocaleTimeString()}
                            stroke="hsl(var(--muted-foreground))"
                            fontSize={12}
                        />

                        {/* Y-Axis (Percentage) */}
                        <YAxis
                            stroke="hsl(var(--muted-foreground))"
                            fontSize={12}
                            domain={[0, 100]}
                        />

                        {/* Tooltip */}
                        <Tooltip
                            contentStyle={{
                                background: 'hsl(var(--card))',
                                border: '1px solid hsl(var(--border))',
                                borderRadius: '8px'
                            }}
                            labelStyle={{ color: 'hsl(var(--foreground))' }}
                            formatter={(value: number) => `${value.toFixed(1)}%`}
                        />

                        {/* CPU Area */}
                        <Area
                            type="monotone"
                            dataKey="cpu"
                            stroke="hsl(220 100% 50%)"
                            fill="hsl(220 100% 50% / 0.2)"
                            name="CPU Load"
                        />

                        {/* RAM Area */}
                        <Area
                            type="monotone"
                            dataKey="ram_percent"
                            stroke="hsl(270 100% 50%)"
                            fill="hsl(270 100% 50% / 0.2)"
                            name="RAM Usage"
                        />
                    </AreaChart>
                </ResponsiveContainer>
            </CardContent>
        </Card>
    );
}
