import { Link } 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 default function ResetForm() {
	const form = useAppForm({
		defaultValues: {
			email: "",
		},
		onSubmit: async ({ value }) => {
			const { data, error } = await authClient.requestPasswordReset({
				email: value.email,
				redirectTo: `${window.location.origin}`,
			});

			if (data) {
				toast.success(data.message);
			}

			if (error) {
				toast.error(error.message);
			}
		},
	});

	return (
		<div className="flex justify-center mt-2">
			<Card className="p-6 w-96">
				<CardHeader>
					<CardTitle>Reset your password</CardTitle>
					<CardDescription>
						Enter your email address and we’ll send you a reset link
					</CardDescription>
				</CardHeader>
				<CardContent>
					<form
						onSubmit={(e) => {
							e.preventDefault();
							form.handleSubmit();
						}}
					>
						<form.AppField name="email">
							{(field) => (
								<field.InputField label="Email" inputType="email" required />
							)}
						</form.AppField>

						<div className="flex justify-end mt-6">
							<form.AppForm>
								<form.SubmitButton>Send Reset Link</form.SubmitButton>
							</form.AppForm>
						</div>
					</form>

					<div className="mt-6 text-center text-sm text-gray-600">
						Remembered your password?{" "}
						<Link
							to="/login"
							className="text-primary underline underline-offset-4 hover:text-primary/80"
						>
							Back to login
						</Link>
					</div>
				</CardContent>
			</Card>
		</div>
	);
}
