"use client";
import { Loader2, User as UserIcon } from "lucide-react";
import Link from "next/link";
import { signOut, useSession } from "next-auth/react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "@/components/ui/popover";

export function AccountPopover() {
	const session = useSession();
	const [loading, setLoading] = useState(false);

	if (session.status === "loading") {
		<Button variant={"outline"} disabled>
			<Loader2 className="animate-spin" />
		</Button>;
	}
	return (
		<Popover>
			<PopoverTrigger asChild>
				<Button className="w-fit px-2" variant="outline">
					<UserIcon />
				</Button>
			</PopoverTrigger>
			<PopoverContent className="w-fit mr-4">
				<div className="grid gap-4">
					<div className="space-y-2">
						<h4 className="font-medium leading-none">
							{session.data?.user?.first_name} {session.data?.user?.last_name}
						</h4>
						<div className="text-sm text-muted-foreground">
							<p className="font-semibold">{session.data?.user?.id_card}</p>
							<p>{session.data?.user?.mobile}</p>
						</div>
					</div>
					<div className="flex flex-col gap-2">
						<Button
							disabled={loading}
							onClick={async () => {
								setLoading(true);
								await signOut();
								setLoading(false);
							}}
						>
							{loading ? <Loader2 className="animate-spin" /> : "Logout"}
						</Button>
						<Link href="/profile" className="text-muted-foreground">
							<Button variant={"secondary"} className="w-full">
								View Profile
							</Button>
						</Link>
					</div>
				</div>
			</PopoverContent>
		</Popover>
	);
}
