import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { useAuth } from "@/hooks/useAuth";
import { useEffect } from "react";
import { useToast } from "@/hooks/use-toast";
import { isUnauthorizedError } from "@/lib/authUtils";
import { useMutation } from "@tanstack/react-query";
import { queryClient } from "@/lib/queryClient";
import { apiRequest } from "@/lib/queryClient";
import type { MediaOutletRequest } from "@shared/schema";

export default function SuperAdminDashboard() {
  const { user, isLoading } = useAuth();
  const { toast } = useToast();

  // Redirect if not authenticated or not superadmin
  useEffect(() => {
    if (!isLoading && (!user || user.role !== 'superadmin')) {
      toast({
        title: "Unauthorized",
        description: "You don't have permission to access this page.",
        variant: "destructive",
      });
      setTimeout(() => {
        window.location.href = "/";
      }, 500);
    }
  }, [isLoading, user, toast]);

  const { data: analytics, isLoading: analyticsLoading, error: analyticsError } = useQuery({
    queryKey: ["/api/analytics"],
    retry: false,
  });

  const { data: requests = [], isLoading: requestsLoading, error: requestsError } = useQuery<MediaOutletRequest[]>({
    queryKey: ["/api/media-outlet-requests"],
    retry: false,
  });

  // Handle analytics errors
  useEffect(() => {
    if (analyticsError && isUnauthorizedError(analyticsError as Error)) {
      toast({
        title: "Unauthorized",
        description: "You are logged out. Logging in again...",
        variant: "destructive",
      });
      setTimeout(() => {
        window.location.href = "/api/login";
      }, 500);
    }
  }, [analyticsError, toast]);

  // Handle requests errors
  useEffect(() => {
    if (requestsError && isUnauthorizedError(requestsError as Error)) {
      toast({
        title: "Unauthorized",
        description: "You are logged out. Logging in again...",
        variant: "destructive",
      });
      setTimeout(() => {
        window.location.href = "/api/login";
      }, 500);
    }
  }, [requestsError, toast]);

  const updateRequestMutation = useMutation({
    mutationFn: async ({ id, status }: { id: string; status: string }) => {
      await apiRequest("PATCH", `/api/media-outlet-requests/${id}`, { status });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/media-outlet-requests"] });
      toast({
        title: "Success",
        description: "Request status updated successfully.",
      });
    },
    onError: (error: Error) => {
      if (isUnauthorizedError(error)) {
        toast({
          title: "Unauthorized",
          description: "You are logged out. Logging in again...",
          variant: "destructive",
        });
        setTimeout(() => {
          window.location.href = "/api/login";
        }, 500);
        return;
      }
      toast({
        title: "Error",
        description: "Failed to update request status.",
        variant: "destructive"
      });
    }
  });

  const handleLogout = () => {
    window.location.href = "/api/logout";
  };

  const handleRequestAction = (id: string, status: string) => {
    updateRequestMutation.mutate({ id, status });
  };

  if (isLoading || !user || user.role !== 'superadmin') {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="bg-card border-b border-border sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="w-10 h-10 bg-primary rounded-lg flex items-center justify-center text-primary-foreground font-bold text-lg">
                S
              </div>
              <span className="text-2xl font-bold tracking-tight">SAPIENS</span>
              <span className="text-sm text-muted-foreground">• Super Admin Dashboard</span>
            </div>
            
            <div className="flex items-center space-x-4">
              <Button variant="ghost" onClick={() => window.location.href = "/"}>
                Home
              </Button>
              <Button variant="outline" onClick={handleLogout}>
                Logout
              </Button>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-6 py-8 pb-24">
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-bold">Super Admin Dashboard</h1>
            <p className="text-muted-foreground">Comprehensive platform analytics and management</p>
          </div>
        </div>
        
        {/* Analytics Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          {analyticsLoading ? (
            Array.from({ length: 4 }).map((_, i) => (
              <Card key={i}>
                <CardContent className="p-6 animate-pulse">
                  <div className="h-16 bg-muted rounded"></div>
                </CardContent>
              </Card>
            ))
          ) : (
            <>
              <Card data-testid="card-total-articles">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="text-sm font-medium text-muted-foreground">Total Articles</h3>
                      <p className="text-2xl font-bold">{(analytics as any)?.totalArticles || 0}</p>
                    </div>
                    <i className="fas fa-newspaper text-primary text-xl"></i>
                  </div>
                </CardContent>
              </Card>
              
              <Card data-testid="card-active-predictions">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="text-sm font-medium text-muted-foreground">Active Predictions</h3>
                      <p className="text-2xl font-bold">{(analytics as any)?.activePredictions || 0}</p>
                    </div>
                    <i className="fas fa-chart-line text-chart-2 text-xl"></i>
                  </div>
                </CardContent>
              </Card>
              
              <Card data-testid="card-live-auctions">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="text-sm font-medium text-muted-foreground">Live Auctions</h3>
                      <p className="text-2xl font-bold">{(analytics as any)?.liveAuctions || 0}</p>
                    </div>
                    <i className="fas fa-gavel text-chart-1 text-xl"></i>
                  </div>
                </CardContent>
              </Card>
              
              <Card data-testid="card-revenue">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="text-sm font-medium text-muted-foreground">Total Revenue</h3>
                      <p className="text-2xl font-bold">${((analytics as any)?.totalRevenue || 0).toLocaleString()}</p>
                    </div>
                    <i className="fas fa-dollar-sign text-chart-4 text-xl"></i>
                  </div>
                </CardContent>
              </Card>
            </>
          )}
        </div>

        {/* Platform Analytics */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
          <Card>
            <CardContent className="p-6">
              <h3 className="text-lg font-semibold mb-4">User Engagement</h3>
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Daily Active Users</span>
                  <span className="font-semibold">1,247</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Avg. Session Duration</span>
                  <span className="font-semibold">12m 34s</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Bounce Rate</span>
                  <span className="font-semibold">32%</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Page Views</span>
                  <span className="font-semibold">15,632</span>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <h3 className="text-lg font-semibold mb-4">Market Performance</h3>
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Total Prediction Volume</span>
                  <span className="font-semibold">$892K</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Auction Participation</span>
                  <span className="font-semibold">78%</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Avg. Bid Amount</span>
                  <span className="font-semibold">$2,150</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Quality Score Avg.</span>
                  <span className="font-semibold">82/100</span>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
        
        {/* Media Outlet Requests */}
        <Card>
          <CardContent className="p-6">
            <h3 className="text-lg font-semibold mb-4">Media Outlet Requests</h3>
            {requestsLoading ? (
              <div className="space-y-3">
                {Array.from({ length: 3 }).map((_, i) => (
                  <div key={i} className="h-16 bg-muted rounded animate-pulse"></div>
                ))}
              </div>
            ) : (requests as MediaOutletRequest[]).length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <i className="fas fa-inbox text-3xl mb-4"></i>
                <p>No pending requests</p>
              </div>
            ) : (
              <div className="space-y-3">
                {requests.filter(r => r.status === 'pending').map((request) => (
                  <div 
                    key={request.id} 
                    className="flex items-center justify-between p-4 border border-border rounded-lg"
                    data-testid={`request-${request.id}`}
                  >
                    <div className="flex-1">
                      <div className="flex items-center space-x-3 mb-2">
                        <p className="font-medium">{request.name}</p>
                        <Badge variant="outline" className="capitalize">
                          {request.category}
                        </Badge>
                        <Badge variant="secondary">
                          {request.status}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground mb-1">{request.description}</p>
                      <p className="text-xs text-muted-foreground">
                        Submitted {request.createdAt ? new Date(request.createdAt).toLocaleDateString() : 'Unknown'}
                      </p>
                    </div>
                    <div className="flex space-x-2">
                      <Button 
                        size="sm" 
                        onClick={() => handleRequestAction(request.id, 'approved')}
                        disabled={updateRequestMutation.isPending}
                        data-testid={`button-approve-${request.id}`}
                      >
                        Approve
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline"
                        onClick={() => handleRequestAction(request.id, 'rejected')}
                        disabled={updateRequestMutation.isPending}
                        data-testid={`button-reject-${request.id}`}
                      >
                        Reject
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
