// System Health Dashboard Component
// Real-time RAM/CPU/DB monitoring with emergency controls

import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { LineChart, Line, YAxis, XAxis, Tooltip, ResponsiveContainer } from 'recharts';
import { AlertTriangle, Zap, Database, Lock, TrendingUp } from 'lucide-react';
import { Button } from '@/components/ui/button';

interface HealthData {
    timestamp: string;
    status: 'healthy' | 'warning' | 'critical';
    system: {
        process: {
            memory: { usage: number; percentage: number; limit: number };
            cpu: number;
            uptime: number;
        };
        database: {
            activeConnections: number;
            stuckLocks: number;
            longRunningQueries: number;
            oldestQueryAge: number | null;
        };
        status: 'healthy' | 'warning' | 'critical';
        alerts: string[];
    };
    alerts: string[];
}

export default function HealthDash() {
    const queryClient = useQueryClient();
    const [history, setHistory] = useState<Array<{ time: string; memory: number; cpu: number }>>([]);

    const { data, isLoading } = useQuery<HealthData>({
        queryKey: ['system-health'],
        queryFn: async () => {
            const response = await fetch('/api/shim/health', {
                headers: {
                    'Authorization': `Bearer ${import.meta.env.PUBLIC_GOD_MODE_TOKEN || 'local-dev-token'}`
                }
            });

            if (!response.ok) throw new Error('Health check failed');

            const data = await response.json();

            // Update history for charts
            setHistory(prev => {
                const newEntry = {
                    time: new Date().toLocaleTimeString(),
                    memory: data.system.process.memory.percentage,
                    cpu: data.system.process.cpu
                };
                return [...prev.slice(-20), newEntry]; // Keep last 20 points
            });

            return data;
        },
        refetchInterval: 2000, // Poll every 2 seconds
        staleTime: 1000,
    });

    const killLocksMutation = useMutation({
        mutationFn: async () => {
            const response = await fetch('/api/shim/emergency/kill-locks', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${import.meta.env.PUBLIC_GOD_MODE_TOKEN || 'local-dev-token'}`
                }
            });

            if (!response.ok) throw new Error('Failed to kill locks');
            return response.json();
        },
        onSuccess: (data) => {
            alert(`✅ Killed ${data.killedCount} stuck locks`);
            queryClient.invalidateQueries({ queryKey: ['system-health'] });
        },
        onError: (error) => {
            alert(`❌ Failed to kill locks: ${error.message}`);
        }
    });

    if (isLoading || !data) {
        return (
            <div className="p-8 text-center text-slate-400">
                Loading system health...
            </div>
        );
    }

    const system = data.system;

    return (
        <div className="space-y-6">

            {/* Alert Banner */}
            {data.alerts.length > 0 && (
                <div className={`p-4 rounded-lg border ${data.status === 'critical'
                        ? 'bg-red-900/20 border-red-700'
                        : 'bg-yellow-900/20 border-yellow-700'
                    }`}>
                    <div className="flex items-start gap-3">
                        <AlertTriangle className={`w-6 h-6 mt-1 ${data.status === 'critical' ? 'text-red-400' : 'text-yellow-400'
                            }`} />
                        <div className="flex-1">
                            <h3 className={`font-semibold ${data.status === 'critical' ? 'text-red-400' : 'text-yellow-400'
                                }`}>
                                {data.status === 'critical' ? '🚨 CRITICAL ALERTS' : '⚠️ WARNINGS'}
                            </h3>
                            <ul className="mt-2 space-y-1">
                                {data.alerts.map((alert, i) => (
                                    <li key={i} className={`text-sm ${data.status === 'critical' ? 'text-red-300' : 'text-yellow-300'
                                        }`}>
                                        {alert}
                                    </li>
                                ))}
                            </ul>
                        </div>
                    </div>
                </div>
            )}

            {/* Metrics Grid */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">

                {/* RAM Usage */}
                <div className={`border p-6 rounded-lg ${system.process.memory.percentage > 90
                        ? 'border-red-500 bg-red-900/10'
                        : system.process.memory.percentage > 75
                            ? 'border-yellow-500 bg-yellow-900/10'
                            : 'border-green-500 bg-green-900/10'
                    }`}>
                    <div className="flex items-center justify-between mb-2">
                        <h3 className="text-sm font-medium text-slate-400 flex items-center gap-2">
                            <Zap className="w-4 h-4" />
                            RAM USAGE
                        </h3>
                        <span className={`text-3xl font-bold ${system.process.memory.percentage > 90 ? 'text-red-400' :
                                system.process.memory.percentage > 75 ? 'text-yellow-400' :
                                    'text-green-400'
                            }`}>
                            {system.process.memory.percentage}%
                        </span>
                    </div>
                    <div className="h-2 bg-slate-900 rounded-full overflow-hidden mt-3">
                        <div
                            className={`h-full transition-all ${system.process.memory.percentage > 90 ? 'bg-red-500' :
                                    system.process.memory.percentage > 75 ? 'bg-yellow-500' :
                                        'bg-green-500'
                                }`}
                            style={{ width: `${system.process.memory.percentage}%` }}
                        />
                    </div>
                    <p className="mt-2 text-xs text-slate-500">
                        {system.process.memory.usage} MB / {system.process.memory.limit} MB
                    </p>
                </div>

                {/* DB Connections */}
                <div className={`border p-6 rounded-lg ${system.database.activeConnections > 100
                        ? 'border-yellow-500 bg-yellow-900/10'
                        : 'border-blue-500 bg-blue-900/10'
                    }`}>
                    <div className="flex items-center justify-between mb-2">
                        <h3 className="text-sm font-medium text-slate-400 flex items-center gap-2">
                            <Database className="w-4 h-4" />
                            DB CONNECTIONS
                        </h3>
                        <span className={`text-3xl font-bold ${system.database.activeConnections > 100 ? 'text-yellow-400' : 'text-blue-400'
                            }`}>
                            {system.database.activeConnections}
                        </span>
                    </div>
                    <p className="text-xs text-slate-500 mt-3">
                        Limit: 10,000 • {system.database.longRunningQueries} long queries
                    </p>
                    {system.database.oldestQueryAge && (
                        <p className="text-xs text-yellow-400 mt-1">
                            Oldest: {system.database.oldestQueryAge}s
                        </p>
                    )}
                </div>

                {/* Stuck Locks */}
                <div className={`border p-6 rounded-lg ${system.database.stuckLocks > 0
                        ? 'border-red-500 bg-red-900/10'
                        : 'border-gray-500 bg-gray-900/10'
                    }`}>
                    <div className="flex items-center justify-between mb-2">
                        <h3 className="text-sm font-medium text-slate-400 flex items-center gap-2">
                            <Lock className="w-4 h-4" />
                            STUCK LOCKS
                        </h3>
                        <span className={`text-3xl font-bold ${system.database.stuckLocks > 0 ? 'text-red-400' : 'text-gray-400'
                            }`}>
                            {system.database.stuckLocks}
                        </span>
                    </div>
                    {system.database.stuckLocks > 0 && (
                        <Button
                            onClick={() => {
                                if (confirm(`⚠️ EMERGENCY: Kill ${system.database.stuckLocks} stuck locks?\n\nThis will terminate blocking queries. Continue?`)) {
                                    killLocksMutation.mutate();
                                }
                            }}
                            disabled={killLocksMutation.isPending}
                            className="w-full mt-3 bg-red-600 hover:bg-red-500 text-white"
                        >
                            {killLocksMutation.isPending ? 'Killing...' : '🚨 KILL ALL'}
                        </Button>
                    )}
                    {system.database.stuckLocks === 0 && (
                        <p className="text-xs text-gray-500 mt-3">No blocking queries</p>
                    )}
                </div>

            </div>

            {/* Charts */}
            {history.length > 5 && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">

                    {/* Memory Chart */}
                    <div className="bg-slate-800 border border-slate-700 rounded-lg p-4">
                        <h3 className="text-white font-semibold mb-4 flex items-center gap-2">
                            <TrendingUp className="w-4 h-4" />
                            Memory Trend (Last 40s)
                        </h3>
                        <ResponsiveContainer width="100%" height={150}>
                            <LineChart data={history}>
                                <XAxis dataKey="time" tick={{ fontSize: 10, fill: '#64748b' }} />
                                <YAxis domain={[0, 100]} tick={{ fontSize: 10, fill: '#64748b' }} />
                                <Tooltip
                                    contentStyle={{ backgroundColor: '#1e293b', border: '1px solid #475569' }}
                                    labelStyle={{ color: '#94a3b8' }}
                                />
                                <Line
                                    type="monotone"
                                    dataKey="memory"
                                    stroke="#f59e0b"
                                    strokeWidth={2}
                                    dot={false}
                                />
                            </LineChart>
                        </ResponsiveContainer>
                    </div>

                    {/* CPU Chart */}
                    <div className="bg-slate-800 border border-slate-700 rounded-lg p-4">
                        <h3 className="text-white font-semibold mb-4 flex items-center gap-2">
                            <TrendingUp className="w-4 h-4" />
                            CPU Trend (Last 40s)
                        </h3>
                        <ResponsiveContainer width="100%" height={150}>
                            <LineChart data={history}>
                                <XAxis dataKey="time" tick={{ fontSize: 10, fill: '#64748b' }} />
                                <YAxis domain={[0, 100]} tick={{ fontSize: 10, fill: '#64748b' }} />
                                <Tooltip
                                    contentStyle={{ backgroundColor: '#1e293b', border: '1px solid #475569' }}
                                    labelStyle={{ color: '#94a3b8' }}
                                />
                                <Line
                                    type="monotone"
                                    dataKey="cpu"
                                    stroke="#3b82f6"
                                    strokeWidth={2}
                                    dot={false}
                                />
                            </LineChart>
                        </ResponsiveContainer>
                    </div>

                </div>
            )}

            {/* System Info */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                <div className="p-3 bg-slate-800 rounded border border-slate-700">
                    <div className="text-slate-500 text-xs">CPU Load</div>
                    <div className="text-white font-semibold text-lg">{system.process.cpu}%</div>
                </div>
                <div className="p-3 bg-slate-800 rounded border border-slate-700">
                    <div className="text-slate-500 text-xs">Uptime</div>
                    <div className="text-white font-semibold text-lg">
                        {Math.floor(system.process.uptime / 3600)}h {Math.floor((system.process.uptime % 3600) / 60)}m
                    </div>
                </div>
                <div className="p-3 bg-slate-800 rounded border border-slate-700">
                    <div className="text-slate-500 text-xs">Status</div>
                    <div className={`font-semibold text-lg ${data.status === 'healthy' ? 'text-green-400' :
                            data.status === 'warning' ? 'text-yellow-400' :
                                'text-red-400'
                        }`}>
                        {data.status.toUpperCase()}
                    </div>
                </div>
                <div className="p-3 bg-slate-800 rounded border border-slate-700">
                    <div className="text-slate-500 text-xs">Last Check</div>
                    <div className="text-white font-semibold text-lg">
                        {new Date(data.timestamp).toLocaleTimeString()}
                    </div>
                </div>
            </div>

        </div>
    );
}
