import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { RefreshButton } from '@/components/ui/refresh-button';
import { SystemHealthStatus } from '@/components/admin/SystemHealthStatus';
import { GroupedAlertsPanel } from '@/components/admin/GroupedAlertsPanel';
import { CorrelatedAlertsPanel } from '@/components/admin/CorrelatedAlertsPanel';
import { IncidentsPanel } from '@/components/admin/IncidentsPanel';
import { AnomalyDetectionPanel } from '@/components/admin/AnomalyDetectionPanel';
import { DataRetentionPanel } from '@/components/admin/DataRetentionPanel';
import { MonitoringQuickStats } from '@/components/admin/MonitoringQuickStats';
import { RecentActivityTimeline } from '@/components/admin/RecentActivityTimeline';
import { MonitoringNavCards } from '@/components/admin/MonitoringNavCards';
import { useSystemHealth } from '@/hooks/useSystemHealth';
import { useGroupedAlerts } from '@/hooks/admin/useGroupedAlerts';
import { useCorrelatedAlerts } from '@/hooks/admin/useCorrelatedAlerts';
import { useIncidents } from '@/hooks/admin/useIncidents';
import { useAnomalyDetections } from '@/hooks/admin/useAnomalyDetection';
import { useRecentActivity } from '@/hooks/admin/useRecentActivity';
import { useDatabaseHealth } from '@/hooks/admin/useDatabaseHealth';
import { useModerationHealth } from '@/hooks/admin/useModerationHealth';
import { useRateLimitStats } from '@/hooks/useRateLimitMetrics';
import { queryKeys } from '@/lib/queryKeys';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';

export default function MonitoringOverview() {
  const queryClient = useQueryClient();
  const [autoRefresh, setAutoRefresh] = useState(true);

  // Fetch all monitoring data
  const systemHealth = useSystemHealth();
  const groupedAlerts = useGroupedAlerts({ includeResolved: false });
  const correlatedAlerts = useCorrelatedAlerts();
  const incidents = useIncidents('open');
  const anomalies = useAnomalyDetections();
  const recentActivity = useRecentActivity(3600000); // 1 hour
  const dbHealth = useDatabaseHealth();
  const moderationHealth = useModerationHealth();
  const rateLimitStats = useRateLimitStats(3600000); // 1 hour

  const isLoading = 
    systemHealth.isLoading ||
    groupedAlerts.isLoading ||
    correlatedAlerts.isLoading ||
    incidents.isLoading ||
    anomalies.isLoading ||
    recentActivity.isLoading ||
    dbHealth.isLoading ||
    moderationHealth.isLoading ||
    rateLimitStats.isLoading;

  const handleRefresh = async () => {
    await queryClient.invalidateQueries({ 
      queryKey: ['monitoring'],
      refetchType: 'active' 
    });
    await queryClient.invalidateQueries({ 
      queryKey: ['system-health'],
      refetchType: 'active' 
    });
    await queryClient.invalidateQueries({ 
      queryKey: ['system-alerts'],
      refetchType: 'active' 
    });
    await queryClient.invalidateQueries({ 
      queryKey: ['rate-limit'],
      refetchType: 'active' 
    });
    await queryClient.invalidateQueries({
      queryKey: queryKeys.monitoring.groupedAlerts(),
      refetchType: 'active'
    });
    await queryClient.invalidateQueries({
      queryKey: queryKeys.monitoring.correlatedAlerts(),
      refetchType: 'active'
    });
    await queryClient.invalidateQueries({
      queryKey: queryKeys.monitoring.incidents(),
      refetchType: 'active'
    });
    await queryClient.invalidateQueries({
      queryKey: queryKeys.monitoring.anomalyDetections(),
      refetchType: 'active'
    });
  };

  // Calculate error count for nav card (from recent activity)
  const errorCount = recentActivity.data?.filter(e => e.type === 'error').length || 0;
  
  // Calculate stats from grouped alerts and incidents
  const totalGroupedAlerts = groupedAlerts.data?.reduce((sum, g) => sum + g.unresolved_count, 0) || 0;
  const recurringIssues = groupedAlerts.data?.filter(g => g.is_recurring).length || 0;
  const activeIncidents = incidents.data?.length || 0;
  const criticalIncidents = incidents.data?.filter(i => i.severity === 'critical').length || 0;

  return (
    <AdminLayout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">Monitoring Overview</h1>
            <p className="text-muted-foreground mt-2">Real-time system health, alerts, and activity monitoring</p>
          </div>
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
              <Switch
                id="auto-refresh"
                checked={autoRefresh}
                onCheckedChange={setAutoRefresh}
              />
              <Label htmlFor="auto-refresh" className="text-sm cursor-pointer">
                Auto-refresh
              </Label>
            </div>
            <RefreshButton
              onRefresh={handleRefresh}
              isLoading={isLoading}
            />
          </div>
        </div>

        {/* System Health Status */}
        <SystemHealthStatus
          systemHealth={systemHealth.data ?? undefined}
          dbHealth={dbHealth.data}
          isLoading={systemHealth.isLoading || dbHealth.isLoading}
        />

        {/* Critical Alerts - Now Grouped */}
        <GroupedAlertsPanel
          alerts={groupedAlerts.data}
          isLoading={groupedAlerts.isLoading}
        />

        {/* Correlated Alerts - Potential Incidents */}
        <CorrelatedAlertsPanel
          correlations={correlatedAlerts.data}
          isLoading={correlatedAlerts.isLoading}
        />

        {/* Active Incidents */}
        <IncidentsPanel
          incidents={incidents.data}
          isLoading={incidents.isLoading}
        />

        {/* ML Anomaly Detection */}
        <AnomalyDetectionPanel
          anomalies={anomalies.data}
          isLoading={anomalies.isLoading}
        />

        {/* Data Retention Management */}
        <DataRetentionPanel />

        {/* Quick Stats Grid */}
        <MonitoringQuickStats
          systemHealth={systemHealth.data ?? undefined}
          rateLimitStats={rateLimitStats.data}
          moderationHealth={moderationHealth.data}
        />

        {/* Recent Activity Timeline */}
        <RecentActivityTimeline
          activity={recentActivity.data}
          isLoading={recentActivity.isLoading}
        />

        {/* Quick Navigation Cards */}
        <div>
          <h2 className="text-lg font-semibold mb-4">Detailed Dashboards</h2>
          <MonitoringNavCards
            errorCount={errorCount}
            rateLimitCount={rateLimitStats.data?.blocked_requests}
          />
        </div>
      </div>
    </AdminLayout>
  );
}
