import { Link, useNavigate } from "@tanstack/react-router";
import { toast } from "sonner";
import {
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "@/components/ui/card";
import { LstCard } from "@/components/ui/lstCard";
import { api } from "@/lib/axiosAPI";
import { useAppForm } from "@/lib/formStuff";

export default function ResetPasswordForm({ token }: { token: string }) {
	const navigate = useNavigate();
	const form = useAppForm({
		defaultValues: {
			password: "",
			confirmPassword: "",
		},
		onSubmit: async ({ value }) => {
			if (value.password != value.confirmPassword) {
				toast.error("Passwords do not match");
				return;
			}
			try {
				const res = await api.post("/api/auth/reset-password", {
					newPassword: value.password,
					token: token,
				});
				if (res.status === 200) {
					toast.success("Password has been reset");
					form.reset();
					navigate({ to: "/login" });
				}
			} catch (error) {
				console.log(error);
				// @ts-ignore
				toast.error(error?.response.data.message);
			}
		},
	});

	return (
		<div className="">
			<LstCard className="p-6 w-96">
				<CardHeader>
					<CardTitle>Set a new password</CardTitle>
					<CardDescription>
						Enter your new password below and confirm it to continue
					</CardDescription>
				</CardHeader>

				<CardContent>
					<form
						onSubmit={(e) => {
							e.preventDefault();
							form.handleSubmit();
						}}
					>
						<form.AppField
							name="password"
							children={(field) => (
								<field.InputPasswordField
									label="New Password"
									required={true}
								/>
							)}
						/>

						<form.AppField
							name="confirmPassword"
							// validators={{
							//     onChangeListenTo: ["password"],
							//     onChange: ({ value, fieldApi }) => {
							//         if (
							//             value !==
							//             fieldApi.form.getFieldValue("password")
							//         ) {
							//             return "Passwords do not match";
							//         }
							//         return undefined;
							//     },
							// }}
							children={(field) => (
								<field.InputPasswordField
									label="Confirm Password"
									required={true}
								/>
							)}
						/>

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

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