import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { useAuth } from "@/hooks/useAuth";
import { useEffect } from "react";
import { useToast } from "@/hooks/use-toast";
import { isUnauthorizedError } from "@/lib/authUtils";

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

  // Redirect if not authenticated or not admin
  useEffect(() => {
    if (!isLoading && (!user || user.role !== 'admin')) {
      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,
  });

  // 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]);

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

  if (isLoading || !user || user.role !== 'admin') {
    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">• 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">
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-bold">Admin Dashboard</h1>
            <p className="text-muted-foreground">Manage media outlets and content</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">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>
        
        {/* Admin Actions */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <Card>
            <CardContent className="p-6">
              <h3 className="text-lg font-semibold mb-4">Content Management</h3>
              <div className="space-y-3">
                <Button 
                  className="w-full justify-start" 
                  variant="outline"
                  data-testid="button-create-editorial"
                >
                  <i className="fas fa-plus mr-3 text-primary"></i>
                  Create Featured Editorial
                </Button>
                <Button 
                  className="w-full justify-start" 
                  variant="outline"
                  data-testid="button-pin-comments"
                >
                  <i className="fas fa-thumbtack mr-3 text-chart-2"></i>
                  Pin Comments
                </Button>
                <Button 
                  className="w-full justify-start" 
                  variant="outline"
                  data-testid="button-manage-predictions"
                >
                  <i className="fas fa-chart-bar mr-3 text-chart-1"></i>
                  Manage Prediction Markets
                </Button>
              </div>
            </CardContent>
          </Card>
          
          <Card>
            <CardContent className="p-6">
              <h3 className="text-lg font-semibold mb-4">Quick Actions</h3>
              <div className="space-y-3">
                <div className="flex items-center justify-between p-3 border border-border rounded-lg">
                  <div>
                    <p className="font-medium">Featured Article Priority</p>
                    <p className="text-sm text-muted-foreground">Manage article visibility</p>
                  </div>
                  <Button size="sm" data-testid="button-manage-featured">
                    Manage
                  </Button>
                </div>
                <div className="flex items-center justify-between p-3 border border-border rounded-lg">
                  <div>
                    <p className="font-medium">Auction Controls</p>
                    <p className="text-sm text-muted-foreground">Monitor active auctions</p>
                  </div>
                  <Button size="sm" data-testid="button-view-auctions">
                    <a href="/auctions">View</a>
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </main>
    </div>
  );
}
