"use client";

import { LogIn, LogOut } from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { useIsMobile } from "@/hooks/use-mobile";
import { signOut, useSession } from "@/lib/auth-client";

export default function SignIn() {
	const isMobile = useIsMobile();
	const { data: session, isPending } = useSession();
	const router = useRouter();

	const handleSignOut = async () => {
		try {
			await signOut();
			router.push("/");
		} catch {
			toast.error("Failed to sign out. Please try again.");
		}
	};

	if (isPending) {
		return <Skeleton className="h-8 w-16" />;
	}

	if (session?.user) {
		return (
			<Button
				aria-label={session?.user ? "Sign out" : "Sign in"}
				onClick={handleSignOut}
				variant="ghost"
				size={isMobile ? "icon" : "sm"}
				className="text-xs text-muted-foreground"
			>
				<LogOut className="h-3.5 w-3.5" />
				{isMobile ? null : "Sign Out"}
			</Button>
		);
	}

	return (
		<Button
			aria-label={session?.user ? "Sign out" : "Sign in"}
			onClick={() => router.push("/auth/signin")}
			variant="ghost"
			size={isMobile ? "icon" : "sm"}
			className="text-xs"
		>
			<LogIn className="h-3.5 w-3.5" />
			{isMobile ? null : "Sign In"}
		</Button>
	);
}
