import { useState, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { ScrollArea } from "@/components/ui/scroll-area";
import { 
  Bug, 
  Database, 
  Server, 
  Shield, 
  RefreshCw, 
  CheckCircle, 
  XCircle, 
  AlertTriangle,
  Monitor,
  Network,
  HardDrive,
  Cpu,
  Activity,
  Eye,
  Download,
  Terminal
} from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";

interface SystemHealth {
  database: {
    status: "healthy" | "warning" | "error";
    connectionTime: number;
    activeConnections: number;
    queries: Array<{ query: string; duration: number; status: string }>;
  };
  server: {
    status: "healthy" | "warning" | "error";
    uptime: number;
    memory: { used: number; total: number; percentage: number };
    cpu: { usage: number; cores: number };
    responseTime: number;
  };
  authentication: {
    status: "healthy" | "warning" | "error";
    activeSessions: number;
    failedAttempts: number;
    lastLogin: string;
  };
  api: {
    endpoints: Array<{
      path: string;
      method: string;
      status: "healthy" | "error";
      responseTime: number;
      lastChecked: string;
    }>;
  };
}

interface ErrorLog {
  id: string;
  timestamp: string;
  level: "error" | "warning" | "info";
  message: string;
  stack?: string;
  route?: string;
  userId?: string;
}

export default function SystemDebug() {
  const [activeTab, setActiveTab] = useState("overview");
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { user } = useAuth();
  const { toast } = useToast();

  const { data: systemHealth, refetch: refetchHealth } = useQuery<SystemHealth>({
    queryKey: ["/api/debug/system-health"],
    refetchInterval: 30000, // Refresh every 30 seconds
  });

  const { data: errorLogs, refetch: refetchLogs } = useQuery<ErrorLog[]>({
    queryKey: ["/api/debug/error-logs"],
    refetchInterval: 10000, // Refresh every 10 seconds
  });

  const { data: performanceMetrics, refetch: refetchMetrics } = useQuery({
    queryKey: ["/api/debug/performance"],
    refetchInterval: 5000, // Refresh every 5 seconds
  });

  const refreshAll = async () => {
    setIsRefreshing(true);
    try {
      await Promise.all([
        refetchHealth(),
        refetchLogs(),
        refetchMetrics()
      ]);
      toast({
        title: "System data refreshed",
        description: "All monitoring data has been updated",
      });
    } catch (error) {
      toast({
        title: "Refresh failed",
        description: "Could not update system data",
        variant: "destructive",
      });
    } finally {
      setIsRefreshing(false);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "healthy": return "text-green-600 bg-green-100 border-green-200";
      case "warning": return "text-yellow-600 bg-yellow-100 border-yellow-200";
      case "error": return "text-red-600 bg-red-100 border-red-200";
      default: return "text-gray-600 bg-gray-100 border-gray-200";
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "healthy": return <CheckCircle className="h-4 w-4" />;
      case "warning": return <AlertTriangle className="h-4 w-4" />;
      case "error": return <XCircle className="h-4 w-4" />;
      default: return <Monitor className="h-4 w-4" />;
    }
  };

  const formatUptime = (seconds: number) => {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return `${days}d ${hours}h ${minutes}m`;
  };

  const formatBytes = (bytes: number) => {
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    if (bytes === 0) return '0 Bytes';
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
  };

  const downloadLogs = async () => {
    try {
      const response = await fetch('/api/debug/download-logs');
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `system-logs-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      
      toast({
        title: "Logs downloaded",
        description: "System logs have been downloaded successfully",
      });
    } catch (error) {
      toast({
        title: "Download failed",
        description: "Could not download system logs",
        variant: "destructive",
      });
    }
  };

  return (
    <div className="p-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-gradient-to-br from-red-500 to-orange-600 rounded-lg flex items-center justify-center">
              <Bug className="h-6 w-6 text-white" />
            </div>
            <div>
              <h1 className="text-3xl font-bold text-gray-900">System Debug Console</h1>
              <p className="text-gray-600">Monitor application health and diagnose issues</p>
            </div>
          </div>
          
          <div className="flex items-center space-x-3">
            <Button
              onClick={refreshAll}
              disabled={isRefreshing}
              variant="outline"
              className="flex items-center space-x-2"
            >
              <RefreshCw className={`h-4 w-4 ${isRefreshing ? 'animate-spin' : ''}`} />
              <span>Refresh All</span>
            </Button>
            <Button
              onClick={downloadLogs}
              variant="outline"
              className="flex items-center space-x-2"
            >
              <Download className="h-4 w-4" />
              <span>Download Logs</span>
            </Button>
          </div>
        </div>
        
        <Alert className="mt-4 bg-orange-50 border-orange-200">
          <Shield className="h-4 w-4 text-orange-600" />
          <AlertDescription className="text-orange-800">
            This debug console provides real-time system monitoring. Use this information to diagnose and resolve application issues.
          </AlertDescription>
        </Alert>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList className="grid w-full grid-cols-5">
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="database">Database</TabsTrigger>
          <TabsTrigger value="server">Server</TabsTrigger>
          <TabsTrigger value="logs">Error Logs</TabsTrigger>
          <TabsTrigger value="api">API Status</TabsTrigger>
        </TabsList>

        {/* Overview Tab */}
        <TabsContent value="overview">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {/* System Status Cards */}
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center space-x-2">
                  <Database className="h-5 w-5" />
                  <span>Database</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center justify-between">
                  <Badge className={getStatusColor(systemHealth?.database.status || "error")}>
                    {getStatusIcon(systemHealth?.database.status || "error")}
                    <span className="ml-1 capitalize">{systemHealth?.database.status || "Unknown"}</span>
                  </Badge>
                  <span className="text-sm text-gray-500">
                    {systemHealth?.database.connectionTime || 0}ms
                  </span>
                </div>
                <div className="mt-3 text-sm text-gray-600">
                  Active Connections: {systemHealth?.database.activeConnections || 0}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center space-x-2">
                  <Server className="h-5 w-5" />
                  <span>Server</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center justify-between">
                  <Badge className={getStatusColor(systemHealth?.server.status || "error")}>
                    {getStatusIcon(systemHealth?.server.status || "error")}
                    <span className="ml-1 capitalize">{systemHealth?.server.status || "Unknown"}</span>
                  </Badge>
                  <span className="text-sm text-gray-500">
                    {systemHealth?.server.responseTime || 0}ms
                  </span>
                </div>
                <div className="mt-3 text-sm text-gray-600">
                  Uptime: {formatUptime(systemHealth?.server.uptime || 0)}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center space-x-2">
                  <Shield className="h-5 w-5" />
                  <span>Authentication</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center justify-between">
                  <Badge className={getStatusColor(systemHealth?.authentication.status || "error")}>
                    {getStatusIcon(systemHealth?.authentication.status || "error")}
                    <span className="ml-1 capitalize">{systemHealth?.authentication.status || "Unknown"}</span>
                  </Badge>
                </div>
                <div className="mt-3 text-sm text-gray-600">
                  Active Sessions: {systemHealth?.authentication.activeSessions || 0}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Performance Metrics */}
          <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Cpu className="h-5 w-5" />
                  <span>Resource Usage</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <div className="flex justify-between text-sm mb-1">
                    <span>Memory Usage</span>
                    <span>{systemHealth?.server.memory.percentage || 0}%</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-blue-600 h-2 rounded-full" 
                      style={{ width: `${systemHealth?.server.memory.percentage || 0}%` }}
                    ></div>
                  </div>
                  <div className="text-xs text-gray-500 mt-1">
                    {formatBytes(systemHealth?.server.memory.used || 0)} / {formatBytes(systemHealth?.server.memory.total || 0)}
                  </div>
                </div>
                
                <div>
                  <div className="flex justify-between text-sm mb-1">
                    <span>CPU Usage</span>
                    <span>{systemHealth?.server.cpu.usage || 0}%</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-green-600 h-2 rounded-full" 
                      style={{ width: `${systemHealth?.server.cpu.usage || 0}%` }}
                    ></div>
                  </div>
                  <div className="text-xs text-gray-500 mt-1">
                    {systemHealth?.server.cpu.cores || 0} cores available
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Activity className="h-5 w-5" />
                  <span>Recent Activity</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div className="flex justify-between items-center">
                    <span className="text-sm">Failed Login Attempts</span>
                    <Badge variant="outline">{systemHealth?.authentication.failedAttempts || 0}</Badge>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">Database Queries</span>
                    <Badge variant="outline">{systemHealth?.database.queries?.length || 0}</Badge>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">Error Count (24h)</span>
                    <Badge variant="outline">{errorLogs?.filter(log => log.level === 'error').length || 0}</Badge>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* Database Tab */}
        <TabsContent value="database">
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Database Health</CardTitle>
                <CardDescription>Monitor database performance and connections</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-green-600">{systemHealth?.database.connectionTime || 0}ms</div>
                    <div className="text-sm text-gray-500">Connection Time</div>
                  </div>
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-blue-600">{systemHealth?.database.activeConnections || 0}</div>
                    <div className="text-sm text-gray-500">Active Connections</div>
                  </div>
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-purple-600">{systemHealth?.database.queries?.length || 0}</div>
                    <div className="text-sm text-gray-500">Recent Queries</div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {systemHealth?.database.queries && (
              <Card>
                <CardHeader>
                  <CardTitle>Recent Database Queries</CardTitle>
                </CardHeader>
                <CardContent>
                  <ScrollArea className="h-64">
                    <div className="space-y-2">
                      {systemHealth.database.queries.map((query, index) => (
                        <div key={index} className="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                          <div className="flex-1">
                            <code className="text-sm text-gray-800">{query.query}</code>
                          </div>
                          <div className="flex items-center space-x-2">
                            <Badge variant="outline">{query.duration}ms</Badge>
                            <Badge className={query.status === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}>
                              {query.status}
                            </Badge>
                          </div>
                        </div>
                      ))}
                    </div>
                  </ScrollArea>
                </CardContent>
              </Card>
            )}
          </div>
        </TabsContent>

        {/* Server Tab */}
        <TabsContent value="server">
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Server Performance</CardTitle>
                <CardDescription>Monitor server resources and performance metrics</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-blue-600">{formatUptime(systemHealth?.server.uptime || 0)}</div>
                    <div className="text-sm text-gray-500">Server Uptime</div>
                  </div>
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-green-600">{systemHealth?.server.responseTime || 0}ms</div>
                    <div className="text-sm text-gray-500">Response Time</div>
                  </div>
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-orange-600">{systemHealth?.server.memory.percentage || 0}%</div>
                    <div className="text-sm text-gray-500">Memory Usage</div>
                  </div>
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-purple-600">{systemHealth?.server.cpu.usage || 0}%</div>
                    <div className="text-sm text-gray-500">CPU Usage</div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* Error Logs Tab */}
        <TabsContent value="logs">
          <Card>
            <CardHeader>
              <CardTitle>Error Logs</CardTitle>
              <CardDescription>Recent system errors and warnings</CardDescription>
            </CardHeader>
            <CardContent>
              <ScrollArea className="h-96">
                <div className="space-y-3">
                  {errorLogs?.map((log) => (
                    <div key={log.id} className="p-4 border rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <Badge className={
                          log.level === 'error' ? 'bg-red-100 text-red-800' :
                          log.level === 'warning' ? 'bg-yellow-100 text-yellow-800' :
                          'bg-blue-100 text-blue-800'
                        }>
                          {log.level.toUpperCase()}
                        </Badge>
                        <span className="text-sm text-gray-500">{new Date(log.timestamp).toLocaleString()}</span>
                      </div>
                      <div className="text-sm text-gray-800 mb-2">{log.message}</div>
                      {log.route && (
                        <div className="text-xs text-gray-500">Route: {log.route}</div>
                      )}
                      {log.stack && (
                        <details className="mt-2">
                          <summary className="text-xs text-gray-500 cursor-pointer">Stack Trace</summary>
                          <pre className="text-xs bg-gray-100 p-2 rounded mt-1 overflow-x-auto">{log.stack}</pre>
                        </details>
                      )}
                    </div>
                  )) || (
                    <div className="text-center text-gray-500 py-8">
                      No error logs available
                    </div>
                  )}
                </div>
              </ScrollArea>
            </CardContent>
          </Card>
        </TabsContent>

        {/* API Status Tab */}
        <TabsContent value="api">
          <Card>
            <CardHeader>
              <CardTitle>API Endpoint Status</CardTitle>
              <CardDescription>Health check for all API endpoints</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {systemHealth?.api.endpoints?.map((endpoint, index) => (
                  <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div className="flex items-center space-x-3">
                      <Badge variant="outline" className="font-mono text-xs">
                        {endpoint.method}
                      </Badge>
                      <code className="text-sm">{endpoint.path}</code>
                    </div>
                    <div className="flex items-center space-x-2">
                      <span className="text-sm text-gray-500">{endpoint.responseTime}ms</span>
                      <Badge className={endpoint.status === 'healthy' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}>
                        {endpoint.status}
                      </Badge>
                    </div>
                  </div>
                )) || (
                  <div className="text-center text-gray-500 py-8">
                    No API endpoint data available
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}