import { LogOut, Trash } from "lucide-react";
import { Button } from "../ui/button";
import { clearCache } from "~/lib/utils";
import { Card, CardContent } from "../ui/card";
import { Avatar, AvatarFallback } from "../ui/avatar";
import { logout, type User } from "~/lib/api";
import { Label } from "../ui/label";
import { Badge } from "../ui/badge";
import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router";
import { MatchStudent } from "./match-student";
import { Separator } from "../ui/separator";

export default function Profile({ user }: { user: User }) {
  const navigate = useNavigate();
  const useLogout = () => {
    const queryClient = useQueryClient();

    // Logout, invalidate user cache, and redirect to login
    return async () => {
      try {
        await logout();
        queryClient.removeQueries({ queryKey: ["user"] });
        navigate("/login", { replace: true });
      } catch (error) {
        console.error("Logout failed:", error);
      }
    };
  };

  const handleLogout = useLogout();

  return (
    <Card className="w-full max-w-2xl mx-auto shadow-lg py-6 pb-0">
      <CardContent className="space-y-6">
        {/* Avatar Section */}
        <div className="flex flex-col sm:flex-row items-center gap-4">
          <div className="relative">
            <Avatar className="h-20 w-20 sm:h-24 sm:w-24">
              {/* <AvatarImage src={profile.avatar || "/placeholder.svg"} alt={profile.name} /> */}
              <AvatarFallback className="text-lg">
                {user.fullName
                  .split(" ")
                  .map((n) => n[0])
                  .join("")}
              </AvatarFallback>
            </Avatar>
          </div>
          <div className="text-center sm:text-left">
            <h3 className="text-xl font-semibold">{user.fullName}</h3>
            <p className="text-muted-foreground">{user.email}</p>
            <Badge className="mt-2">{user.className}</Badge>
          </div>
        </div>

        {/* Form Fields */}
        <div className="grid gap-4">
          <div className="grid gap-2">
            <Label htmlFor="name">Nom & Prénom</Label>
            <p className="px-3 py-2 bg-muted rounded-md">{user.fullName}</p>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="email">Adresse Email</Label>
            <p className="px-3 py-2 bg-muted rounded-md">{user.email}</p>
          </div>
        </div>

        {!user.pastStudentId && (
          <>
            <Separator />
            <MatchStudent
              firstName={user.firstName}
              lastName={user.lastName}
              onSuccess={() => {
                window.location.reload();
              }}
            />
          </>
        )}

        <Separator />

        {/* Logout Button */}
        <Button
          variant="destructive"
          className="w-full text-white"
          onClick={handleLogout}
        >
          <LogOut className="mr-2 h-4 w-4" />
          Se déconnecter
        </Button>

        <Button
          variant="outline"
          className="w-full"
          onClick={clearCache}
        >
          <Trash className="mr-2 h-4 w-4" />
          Vider le cache
        </Button>
      </CardContent>
    </Card>
  );
}
