import { useQuery } from "@tanstack/react-query";
import { useAuth, logout } from "@/hooks/use-auth";
import { Header } from "@/components/Header";
import { MobileNav } from "@/components/MobileNav";
import { StatCard } from "@/components/StatCard";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Target, TrendingUp, Sparkles, LogOut } from "lucide-react";

export default function Profile() {
  const { user } = useAuth();
  
  const { data: stats } = useQuery<{ totalPlans: number; avgCompletion: number; aiUsageCount: number }>({
    queryKey: ["/api/user/stats"],
  });

  if (!user) {
    return null;
  }

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

      <main className="container mx-auto px-4 md:px-6 py-6 max-w-4xl space-y-8">
        {/* Profile Header */}
        <div className="flex flex-col md:flex-row items-center md:items-start gap-6">
          <Avatar className="h-24 w-24">
            <AvatarImage src={user.profileImageUrl || undefined} />
            <AvatarFallback className="bg-primary text-primary-foreground text-2xl font-bold">
              {user.firstName?.[0]}{user.lastName?.[0]}
            </AvatarFallback>
          </Avatar>
          <div className="flex-1 text-center md:text-left">
            <h1 className="text-3xl font-bold mb-1" data-testid="text-user-name">
              {user.firstName} {user.lastName}
            </h1>
            <p className="text-muted-foreground mb-4" data-testid="text-user-email">
              {user.email}
            </p>
            <div className="flex gap-2 justify-center md:justify-start">
              <Button variant="outline" size="sm" onClick={logout} data-testid="button-logout">
                <LogOut className="h-4 w-4 mr-2" />
                Logout
              </Button>
            </div>
          </div>
        </div>

        {/* Stats */}
        <div>
          <h2 className="text-xl font-semibold mb-4">Your Stats</h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <StatCard icon={Target} label="Total Plans" value={stats?.totalPlans || 0} />
            <StatCard
              icon={TrendingUp}
              label="Avg Completion"
              value={`${stats?.avgCompletion || 0}%`}
              iconClassName="bg-success/10 text-success"
            />
            <StatCard
              icon={Sparkles}
              label="AI Usage"
              value={stats?.aiUsageCount || 0}
              iconClassName="bg-ai-accent/10 text-ai-accent"
            />
          </div>
        </div>
      </main>

      <MobileNav />
    </div>
  );
}
