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

export default function ChangePassword() {
	const router = useRouter();
	const form = useAppForm({
		defaultValues: {
			currentPassword: "",
			newPassword: "",
			confirmPassword: "",
		},
		onSubmit: async ({ value }) => {
			if (value.newPassword !== value.confirmPassword) {
				toast.error("Passwords do not match");
				return;
			}
			const { data, error } = await authClient.changePassword({
				newPassword: value.newPassword,
				currentPassword: value.currentPassword,
				revokeOtherSessions: true,
			});

			if (data) {
				toast.success("Password has been updated");
				form.reset();
				router.invalidate();

				//navigate({ to: "/login" });
			}

			if (error) {
				toast.success(error.message);
			}
		},
	});
	return (
		<div>
			<Card className="p-6 w-96">
				<CardHeader>
					<CardTitle>Change password</CardTitle>
				</CardHeader>

				<CardContent>
					<form
						onSubmit={(e) => {
							e.preventDefault();
							form.handleSubmit();
						}}
					>
						<form.AppField name="currentPassword">
							{(field) => (
								<field.InputPasswordField
									label="Enter your current password"
									required={true}
								/>
							)}
						</form.AppField>

						<form.AppField name="newPassword">
							{(field) => (
								<field.InputPasswordField
									label="New password"
									required={true}
								/>
							)}
						</form.AppField>

						<form.AppField name="confirmPassword">
							{(field) => (
								<field.InputPasswordField
									label="Re-enter your password"
									required={true}
								/>
							)}
						</form.AppField>

						<div className="flex justify-end mt-6">
							<form.AppForm>
								<form.SubmitButton variant="destructive">
									Update Password
								</form.SubmitButton>
							</form.AppForm>
						</div>
					</form>
				</CardContent>
			</Card>
		</div>
	);
}
