import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { Header } from "@/components/Header";
import { StatCard } from "@/components/StatCard";
import { Users, Target, Sparkles, Shield } from "lucide-react";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

interface UserWithStats {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  planCount: number;
  avgProgress: number;
  aiUsage: number;
}

export default function Admin() {
  const { user } = useAuth();

  const { data: users = [], isLoading } = useQuery<UserWithStats[]>({
    queryKey: ["/api/admin/users"],
    enabled: user?.isAdmin,
  });

  if (!user?.isAdmin) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <Shield className="h-16 w-16 text-muted-foreground mx-auto mb-4" />
          <h2 className="text-2xl font-semibold mb-2">Access Denied</h2>
          <p className="text-muted-foreground">You don't have admin privileges</p>
        </div>
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
          <p className="text-muted-foreground">Loading...</p>
        </div>
      </div>
    );
  }

  const totalPlans = users.reduce((sum, u) => sum + u.planCount, 0);
  const totalAiUsage = users.reduce((sum, u) => sum + u.aiUsage, 0);

  return (
    <div className="min-h-screen bg-background pb-8">
      <Header />

      <main className="container mx-auto px-4 md:px-6 py-6 space-y-8">
        <div className="flex items-center gap-3">
          <Shield className="h-8 w-8 text-primary" />
          <div>
            <h1 className="text-3xl font-bold">Admin Dashboard</h1>
            <p className="text-muted-foreground">Monitor users, plans, and AI usage</p>
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <StatCard icon={Users} label="Total Users" value={users.length} />
          <StatCard
            icon={Target}
            label="Total Plans"
            value={totalPlans}
            iconClassName="bg-success/10 text-success"
          />
          <StatCard
            icon={Sparkles}
            label="AI Queries"
            value={totalAiUsage}
            iconClassName="bg-ai-accent/10 text-ai-accent"
          />
        </div>

        {/* Users Table */}
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>User</TableHead>
                <TableHead>Email</TableHead>
                <TableHead className="text-center">Plans</TableHead>
                <TableHead className="text-center">Avg Progress</TableHead>
                <TableHead className="text-center">AI Usage</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {users.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-muted-foreground py-8">
                    No users found
                  </TableCell>
                </TableRow>
              ) : (
                users.map((u) => (
                  <TableRow key={u.id}>
                    <TableCell className="font-medium">
                      {u.firstName} {u.lastName}
                    </TableCell>
                    <TableCell>{u.email}</TableCell>
                    <TableCell className="text-center">{u.planCount}</TableCell>
                    <TableCell className="text-center">
                      <Badge variant="secondary">{u.avgProgress}%</Badge>
                    </TableCell>
                    <TableCell className="text-center">{u.aiUsage}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </Card>
      </main>
    </div>
  );
}
