import { createFileRoute, redirect } from "@tanstack/react-router";
import { Suspense } from "react";
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 { Spinner } from "../../components/ui/spinner";
import ChangePassword from "./-components/ChangePassword";
import NotificationsSubCard from "./-components/NotificationsSubCard";
import NotificationsTable from "./-components/NotificationsTable";

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">
			<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>
					<Suspense
						fallback={
							<Card className="p-3 w-lg">
								<CardHeader>
									<CardTitle>Notifications</CardTitle>
								</CardHeader>
								<CardContent>
									<div className="flex justify-center m-auto">
										<div>
											<Spinner className="size-32" />
										</div>
									</div>
								</CardContent>
							</Card>
						}
					>
						{session && <NotificationsSubCard user={session.user} />}
					</Suspense>
				</div>
			</div>
			<div className="w-fill">
				<Suspense
					fallback={
						<Card className="p-3">
							<CardHeader>
								<CardTitle className="text-center">Subscriptions</CardTitle>
							</CardHeader>
							<CardContent>
								<div className="flex justify-center m-auto">
									<div>
										<Spinner className="size-32" />
									</div>
								</div>
							</CardContent>
						</Card>
					}
				>
					{session && <NotificationsTable userId={`${session.user.id}`} />}
				</Suspense>
			</div>
		</div>
	);
}
