import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { toast } from "sonner";
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "@/components/ui/card";
import { authClient } from "@/lib/auth-client";
import { useAppForm } from "@/lib/formSutff";

export const Route = createFileRoute("/(auth)/user/signup")({
	component: RouteComponent,
});

function RouteComponent() {
	const navigate = useNavigate();
	const form = useAppForm({
		defaultValues: {
			name: "",
			email: "",
			password: "",
			confirmPassword: "",
		},
		onSubmit: async ({ value }) => {
			if (value.password !== value.confirmPassword) {
				toast.error("Passwords do not match");
				return;
			}

			const { data, error } = await authClient.signUp.email({
				name: value.name,
				email: value.email,
				password: value.password,
				callbackURL: `${window.location.origin}/lst/app`,
			});

			if (data) {
				toast.success(`Welcome ${value.name}, to lst.`);
				navigate({ to: "/" });
			}

			if (error) {
				toast.error(error.message);
			}
		},
	});
	return (
		<div className="flex justify-center mt-2">
			<Card className="p-6 w-96">
				<CardHeader>
					<CardTitle>Create an account</CardTitle>
					<CardDescription>Fill in your details to get started</CardDescription>
				</CardHeader>

				<CardContent>
					<form
						onSubmit={(e) => {
							e.preventDefault();
							form.handleSubmit();
						}}
					>
						{/* Username */}
						<form.AppField name="name">
							{(field) => (
								<field.InputField
									label="Name"
									inputType="text"
									required={true}
								/>
							)}
						</form.AppField>

						{/* Email */}
						<form.AppField name="email">
							{(field) => (
								<field.InputField
									label="Email address"
									inputType="email"
									required={true}
								/>
							)}
						</form.AppField>

						{/* Password */}
						<form.AppField name="password">
							{(field) => (
								<field.InputField
									label="Password"
									inputType="password"
									required={true}
								/>
							)}
						</form.AppField>

						{/* Confirm Password */}
						<form.AppField name="confirmPassword">
							{(field) => (
								<field.InputField
									label="Confirm Password"
									inputType="password"
									required={true}
								/>
							)}
						</form.AppField>

						<div className="flex justify-end mt-6">
							<form.AppForm>
								<form.SubmitButton>Sign Up</form.SubmitButton>
							</form.AppForm>
						</div>
					</form>

					<div className="mt-6 text-center text-sm text-gray-600">
						Already have an account?{" "}
						<Link
							to={"/login"}
							className="text-primary underline underline-offset-4 hover:text-primary/80"
						>
							Log in
						</Link>
					</div>
				</CardContent>
			</Card>
		</div>
	);
}
