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

export const Route = createFileRoute("/(auth)/user/profile")({
	beforeLoad: async () => {
		const result = await authClient.getSession({
			query: { disableCookieCache: true }, // force DB/Server lookup
		});

		//console.log("session check:", result.data);

		if (!result.data) {
			throw redirect({
				to: "/login",
				search: {
					redirect: location.pathname + location.search,
				},
			});
		}
	},
	component: RouteComponent,
});

function RouteComponent() {
	const { data: session } = useSession();
	const form = useAppForm({
		defaultValues: {
			name: session?.user.name,
		},
		onSubmit: async ({ value }) => {
			const { data, error } = await authClient.updateUser({
				name: value.name,
			});

			if (data) {
				toast.success("Profile has been updated");
				form.reset();
				//navigate({ to: "/login" });
			}

			if (error) {
				toast.success(error.message);
			}
		},
	});
	return (
		<div className="flex justify-center flex-col pt-4 gap-2 lg:flex-row">
			<div>
				<Card className="p-6 w-96">
					<CardHeader>
						<CardTitle>Profile</CardTitle>
						<CardDescription>
							Change your profile and password below
						</CardDescription>
					</CardHeader>

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

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