"use client";
import { signIn, useSession } from "next-auth/react";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { Toaster } from "react-hot-toast";

export const Login = () => {
	const [isLoading, setIsLoading] = useState(false);
	const searchParams = useSearchParams();
	const { data: session } = useSession();
	const navigate = useRouter();

	useEffect(() => {
		if (session) {
			navigate.push("/");
		}
	}, [session, navigate]);

	useEffect(() => {
		const signInWithCode = async () => {
			const code = searchParams.get("code");
			if (code) {
				setIsLoading(true);
				await signIn("credentials", {
					code: code,
					callbackUrl: "/",
				});
				setIsLoading(false);
			}
		};
		signInWithCode();
	}, [searchParams]);

	return (
		<div className="card-body">
			<div>
				<Toaster position="top-center" reverseOrder={false} />
			</div>
			<h1 className="text-3xl font-bold">Login</h1>
			<span className="text-sm font-medium">
				Noch keinen Account? Zur{" "}
				<a
					href={`${process.env.NEXT_PUBLIC_HUB_URL}/register`}
					className="link link-accent link-hover"
				>
					Registrierung
				</a>
			</span>

			<div className="form-control mt-6">
				<a
					href={`${process.env.NEXT_PUBLIC_HUB_URL}/oauth?service=${encodeURIComponent(process.env.NEXT_PUBLIC_SERVICE_ID || "")}&redirect_uri=${encodeURIComponent(`${process.env.NEXT_PUBLIC_PUBLIC_URL}/login`)}`}
				>
					<button
						className="btn btn-primary"
						name="loginBtn"
						disabled={isLoading}
					>
						{isLoading && (
							<span className="loading loading-spinner loading-sm"></span>
						)}
						Login{isLoading && "..."}
					</button>
				</a>
			</div>
		</div>
	);
};
