// Real-time monitoring component
// Auto-refreshes pool stats and database health

import React, { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Loader2, AlertTriangle, CheckCircle } from 'lucide-react';

interface HealthData {
    timestamp: string;
    pool: {
        totalCount: number;
        idleCount: number;
        waitingCount: number;
        maxConnections: number;
        utilizationPercent: number;
        status: 'healthy' | 'warning' | 'critical';
        message: string;
    };
    database: {
        databaseSize: string;
        tableStats: Array<{ table: string; rowCount: number; tableSize: string }>;
    };
    vacuum: {
        recommended: boolean;
        candidates: Array<{
            table: string;
            deadTuples: number;
            liveTuples: number;
            deadPercent: number;
        }>;
    };
    status: string;
}

export default function ShimMonitor() {
    const [lastUpdate, setLastUpdate] = useState<Date>(new Date());

    const { data, isLoading, error, refetch } = useQuery<HealthData>({
        queryKey: ['shim-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();
            setLastUpdate(new Date());
            return data;
        },
        refetchInterval: 5000, // Auto-refresh every 5 seconds
        staleTime: 4000,
    });

    if (isLoading) {
        return (
            <div className="flex items-center justify-center p-8">
                <Loader2 className="w-6 h-6 text-blue-500 animate-spin mr-3" />
                <span className="text-slate-400">Loading health data...</span>
            </div>
        );
    }

    if (error) {
        return (
            <div className="p-4 bg-red-900/20 border border-red-700 rounded-lg">
                <div className="flex items-center gap-2 text-red-400">
                    <AlertTriangle className="w-5 h-5" />
                    <span className="font-semibold">Health check failed</span>
                </div>
                <p className="text-red-300 text-sm mt-2">{(error as Error).message}</p>
                <button
                    onClick={() => refetch()}
                    className="mt-3 px-3 py-1 bg-red-800 hover:bg-red-700 rounded text-white text-sm"
                >
                    Retry
                </button>
            </div>
        );
    }

    if (!data) return null;

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

            {/* Last Update */}
            <div className="flex justify-between items-center text-xs text-slate-500">
                <span>Last updated: {lastUpdate.toLocaleTimeString()}</span>
                <button
                    onClick={() => refetch()}
                    className="px-2 py-1 bg-slate-700 hover:bg-slate-600 rounded text-slate-300"
                >
                    Refresh Now
                </button>
            </div>

            {/* Connection Stats */}
            <div className="grid grid-cols-3 gap-3">
                <div className="p-3 bg-slate-900 rounded-lg">
                    <div className="text-xs text-slate-500 mb-1">Active</div>
                    <div className="text-xl font-bold text-white">
                        {data.pool.totalCount - data.pool.idleCount}
                    </div>
                </div>
                <div className="p-3 bg-slate-900 rounded-lg">
                    <div className="text-xs text-slate-500 mb-1">Idle</div>
                    <div className="text-xl font-bold text-green-400">
                        {data.pool.idleCount}
                    </div>
                </div>
                <div className="p-3 bg-slate-900 rounded-lg">
                    <div className="text-xs text-slate-500 mb-1">Waiting</div>
                    <div className={`text-xl font-bold ${data.pool.waitingCount > 0 ? 'text-red-400' : 'text-gray-400'
                        }`}>
                        {data.pool.waitingCount}
                    </div>
                </div>
            </div>

            {/* Pool Status */}
            <div className={`p-3 rounded-lg border ${data.pool.status === 'healthy'
                    ? 'bg-green-900/20 border-green-700'
                    : data.pool.status === 'warning'
                        ? 'bg-yellow-900/20 border-yellow-700'
                        : 'bg-red-900/20 border-red-700'
                }`}>
                <div className="flex items-center gap-2">
                    {data.pool.status === 'healthy' ? (
                        <CheckCircle className="w-5 h-5 text-green-400" />
                    ) : (
                        <AlertTriangle className="w-5 h-5 text-yellow-400" />
                    )}
                    <span className={`font-semibold ${data.pool.status === 'healthy' ? 'text-green-400' :
                            data.pool.status === 'warning' ? 'text-yellow-400' :
                                'text-red-400'
                        }`}>
                        {data.pool.status.toUpperCase()}
                    </span>
                </div>
                <p className={`text-sm mt-2 ${data.pool.status === 'healthy' ? 'text-green-300' :
                        data.pool.status === 'warning' ? 'text-yellow-300' :
                            'text-red-300'
                    }`}>
                    {data.pool.message}
                </p>
            </div>

            {/* VACUUM Alert */}
            {data.vacuum.recommended && (
                <div className="p-3 bg-purple-900/20 border border-purple-700 rounded-lg">
                    <div className="flex items-center gap-2 text-purple-400 font-semibold mb-2">
                        <span>🧹</span>
                        <span>VACUUM Recommended</span>
                    </div>
                    <p className="text-purple-300 text-sm mb-2">
                        {data.vacuum.candidates.length} table(s) need maintenance
                    </p>
                    <div className="space-y-1">
                        {data.vacuum.candidates.slice(0, 3).map((table) => (
                            <div key={table.table} className="flex justify-between text-xs text-purple-200">
                                <span>{table.table.split('.')[1]}</span>
                                <span>{table.deadPercent.toFixed(1)}% dead</span>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {/* Quick Stats */}
            <div className="grid grid-cols-2 gap-3 text-sm">
                <div className="p-2 bg-slate-900 rounded">
                    <div className="text-slate-500 text-xs">Utilization</div>
                    <div className={`font-bold ${data.pool.utilizationPercent > 90 ? 'text-red-400' :
                            data.pool.utilizationPercent > 70 ? 'text-yellow-400' :
                                'text-green-400'
                        }`}>
                        {data.pool.utilizationPercent}%
                    </div>
                </div>
                <div className="p-2 bg-slate-900 rounded">
                    <div className="text-slate-500 text-xs">DB Size</div>
                    <div className="font-bold text-white">{data.database.databaseSize}</div>
                </div>
            </div>

        </div>
    );
}
