'use client';

import { useState, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { RefreshCw, AlertCircle, Settings } from 'lucide-react';
import { toast } from 'sonner';
import {
  StatsCards,
  SystemOverview,
  LogViewer,
  HTTPStatsOverview,
  HTTPEndpointStats,
  QueueOverview,
  QueueDetails,
} from '@/components/monitoring';
import { useMonitoring, useLogStream } from '@/hooks/use-monitoring';
import { settingsApi } from '@/lib/api';

export default function MonitoringPage() {
  const [activeTab, setActiveTab] = useState('overview');
  const queryClient = useQueryClient();
  const { logs: initialLogs, stats, isLoading, logsError, statsError, refetchLogs, refetchStats, clearLogs, isClearingLogs } = useMonitoring();
  const { logs: liveLogs, status: wsStatus, clearLogs: clearLiveLogs } = useLogStream(activeTab === 'logs');

  // Fetch monitoring enabled setting
  const { data: settings } = useQuery({
    queryKey: ['settings'],
    queryFn: settingsApi.get,
  });

  // Mutation to update monitoring setting
  const updateMonitoringMutation = useMutation({
    mutationFn: (enabled: boolean) => settingsApi.update({ enable_monitoring: enabled }),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['settings'] });
      toast.success(data.enable_monitoring ? 'Monitoring enabled' : 'Monitoring disabled');
    },
    onError: () => {
      toast.error('Failed to update monitoring setting');
    },
  });

  // Combine live logs with initial logs (live logs take precedence)
  const allLogs = useMemo(() => {
    const initial = initialLogs?.logs || [];
    return [...liveLogs, ...initial].slice(0, 1000);
  }, [liveLogs, initialLogs?.logs]);

  const handleRefresh = () => {
    refetchLogs();
    refetchStats();
  };

  const handleClearLogs = () => {
    clearLogs();
    clearLiveLogs();
  };

  const handleMonitoringToggle = () => {
    if (settings) {
      updateMonitoringMutation.mutate(!settings.enable_monitoring);
    }
  };

  const hasError = logsError || statsError;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">System Monitoring</h1>
          <p className="text-muted-foreground">
            Real-time logs and system statistics
          </p>
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <Switch
              id="monitoring-toggle"
              checked={settings?.enable_monitoring ?? true}
              onCheckedChange={handleMonitoringToggle}
              disabled={updateMonitoringMutation.isPending}
            />
            <Label htmlFor="monitoring-toggle" className="text-sm">
              {settings?.enable_monitoring ? 'Enabled' : 'Disabled'}
            </Label>
          </div>
          <Button onClick={handleRefresh} disabled={isLoading}>
            <RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        </div>
      </div>

      {hasError && (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Connection Error</AlertTitle>
          <AlertDescription>
            Unable to connect to the monitoring service. Make sure the API server is running with Redis connected.
          </AlertDescription>
        </Alert>
      )}

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList>
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="logs">Logs</TabsTrigger>
          <TabsTrigger value="api">API Stats</TabsTrigger>
          <TabsTrigger value="worker">Worker Stats</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-4">
          <SystemOverview apiStats={stats?.api} workerStats={stats?.worker} />
          <StatsCards apiStats={stats?.api} workerStats={stats?.worker} />
        </TabsContent>

        <TabsContent value="logs">
          <LogViewer
            logs={allLogs}
            wsStatus={wsStatus}
            isLoading={isLoading}
            onClearLogs={handleClearLogs}
            onRefresh={() => refetchLogs()}
            isClearingLogs={isClearingLogs}
          />
        </TabsContent>

        <TabsContent value="api" className="space-y-4">
          <HTTPStatsOverview stats={stats?.api?.http} />
          <HTTPEndpointStats stats={stats?.api?.http} />
        </TabsContent>

        <TabsContent value="worker" className="space-y-4">
          <QueueOverview stats={stats?.worker?.asynq} />
          <QueueDetails stats={stats?.worker?.asynq} />
        </TabsContent>
      </Tabs>
    </div>
  );
}
