"use client";
import { cn } from "@/lib/utils";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import useLogin from "@/hooks/use-login";
import {
	ActionButton,
	ActionButtonDefault,
	ActionButtonError,
	ActionButtonLoading,
	ActionButtonSuccess,
} from "./action-button";

export function LoginForm({
	className,
	...props
}: React.ComponentPropsWithoutRef<"form">) {
	const [email, setEmail] = useState("");
	const [password, setPassword] = useState("");
	const { login, loading, isSuccess } = useLogin();
	const router = useRouter();
	const searchParams = useSearchParams();

	const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
		e.preventDefault();
		try {
			const res = await login({ email, password });
			if (res.status === "Success") {
				const redirectTo = searchParams.get("redirectTo");
				if (redirectTo) {
					router.push(redirectTo);
				} else {
					router.push("/dashboard");
				}
			}
			console.log(res);
		} catch (err: any) {
			console.log(err.message);
		}
	};

	return (
		<form
			onSubmit={handleSubmit}
			className={cn("flex flex-col gap-6", className)}
			{...props}
		>
			<div className="flex flex-col items-center gap-2 text-center">
				<h1 className="text-2xl font-bold">
					Connectez-vous à votre compte.
				</h1>
				<p className="text-balance text-sm text-muted-foreground">
					Entrez votre adresse e-mail pour vous connecter
				</p>
			</div>
			<div className="grid gap-6">
				<div className="grid gap-2">
					<Label htmlFor="email">E-Mail</Label>
					<Input
						id="email"
						type="email"
						value={email}
						disabled={loading}
						onChange={(e) => setEmail(e.currentTarget.value)}
						placeholder="m@example.com"
						required
					/>
				</div>
				<div className="grid gap-2">
					<div className="flex items-center">
						<Label htmlFor="password">Mot de passe</Label>
						<a
							href="#"
							className="ml-auto text-sm underline-offset-4 hover:underline"
						>
							Mot de passe oublier
						</a>
					</div>
					<Input
						value={password}
						onChange={(e) => setPassword(e.currentTarget.value)}
						disabled={loading}
						id="password"
						type="password"
						required
					/>
				</div>
				<ActionButton
					isLoading={loading}
					isSuccess={isSuccess}
					type="submit"
				>
					<ActionButtonDefault>Se connecter</ActionButtonDefault>
					<ActionButtonLoading />
					<ActionButtonError />
					<ActionButtonSuccess />
				</ActionButton>
			</div>
			{/*<div className="text-center text-sm">
				Pas de compte ?{" "}
				<a href="#" className="underline underline-offset-4">
					Créer un compte
				</a>
			</div>*/}
		</form>
	);
}
