import { Link, useNavigate } from "@tanstack/react-router";
import axios from "axios";
import { toast } from "sonner";
import {
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "../../../../components/ui/card";
import { LstCard } from "../../../../components/ui/lstCard";
import { getSession, useAuth, useUserRoles } from "../../../../lib/authClient";
import { useAppForm } from "../../../../lib/formStuff";

export default function LoginForm({ redirectPath }: { redirectPath: string }) {
	//const search = useSearch({ from: "/_app/(auth)/login" });
	const username = localStorage.getItem("username") || "";
	const rememberMe = localStorage.getItem("rememberMe") === "true";
	const { setSession } = useAuth();
	const { fetchRoles } = useUserRoles();
	const navigate = useNavigate();

	const form = useAppForm({
		defaultValues: {
			username: username,
			password: "",
			rememberMe: rememberMe,
		},
		onSubmit: async ({ value }) => {
			if (value.rememberMe) {
				localStorage.setItem("rememberMe", value.rememberMe.toString());
				localStorage.setItem("username", value.username);
			} else {
				localStorage.removeItem("rememberMe");
				localStorage.removeItem("username");
			}

			try {
				await axios.post("/lst/api/user/login", {
					username: value.username.toLowerCase(),
					password: value.password,
				});

				const session = await getSession();
				setSession(session);
				form.reset();
				fetchRoles();

				toast.success(
					`Welcome back ${session?.user.name ? session?.user.name : session?.user.username} `,
				);
				//router.invalidate();
				if (redirectPath.includes("profile")) {
					navigate({ to: "/" });
				} else {
					navigate({ to: redirectPath });
				}
			} catch (error) {
				// @ts-ignore
				if (!error.response.data.success) {
					// @ts-ignore
					toast.error(error?.response?.data.message);
				} else {
					// @ts-ignore
					toast.error(error?.message);
				}
			}
		},
	});
	return (
		<div className="">
			<LstCard className="p-3 w-96">
				<CardHeader>
					<CardTitle>Login to your account</CardTitle>
					<CardDescription>
						Enter your username and password below
					</CardDescription>
				</CardHeader>
				<CardContent>
					<form
						onSubmit={(e) => {
							e.preventDefault();
							form.handleSubmit();
						}}
					>
						<form.AppField
							name="username"
							children={(field) => (
								<field.InputField
									label="Username"
									inputType="string"
									required={true}
								/>
							)}
						/>
						<form.AppField
							name="password"
							children={(field) => (
								<field.InputPasswordField label="Password" required={true} />
							)}
						/>
						<div className="flex flex-row justify-between mt-3 mb-3">
							<form.AppField
								name="rememberMe"
								children={(field) => (
									<field.CheckboxField label="Remember me" />
								)}
							/>
							<Link
								to="/user/resetpassword"
								className="inline-block text-sm underline-offset-4 hover:underline"
							>
								Forgot your password?
							</Link>
						</div>

						<div className="flex justify-end mt-2">
							<form.AppForm>
								<form.SubmitButton>Login</form.SubmitButton>
							</form.AppForm>
						</div>
					</form>

					<div className="mt-4 text-center text-sm">
						Don&apos;t have an account?{" "}
						<Link to={"/user/signup"} className="underline underline-offset-4">
							Sign up
						</Link>
					</div>
				</CardContent>
			</LstCard>
		</div>
	);
}
