import { Link, useNavigate } from "@tanstack/react-router";
import { Cat } from "lucide-react";
import { toast } from "sonner";
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "@/components/ui/card";
import { authClient } from "@/lib/auth-client";
import { useAppForm } from "@/lib/formSutff";
import { Button } from "../../../components/ui/button";
import socket from "../../../lib/socket.io";

export default function LoginForm({ redirectPath }: { redirectPath: string }) {
	const loginEmail = localStorage.getItem("loginEmail") || "";
	const rememberMe = localStorage.getItem("rememberMe") === "true";

	const navigate = useNavigate();

	const oauthLogin = async () => {
		await authClient.signIn.oauth2({
			providerId: "voidauth",
			callbackURL: "/lst/app",
			errorCallbackURL: "/lst/app/login",
		});
	};

	const form = useAppForm({
		defaultValues: {
			login: loginEmail,
			password: "",
			rememberMe: rememberMe,
		},
		onSubmit: async ({ value }) => {
			// set remember me incase we want it later
			const loginValue = value.login.trim();
			const isEmailLogin = loginValue.includes("@");

			if (value.rememberMe) {
				localStorage.setItem("rememberMe", value.rememberMe.toString());
				localStorage.setItem("loginEmail", loginValue.toLocaleLowerCase());
			} else {
				localStorage.removeItem("rememberMe");
				localStorage.removeItem("loginEmail");
			}

			try {
				const login = isEmailLogin
					? await authClient.signIn.email({
							email: loginValue.toLowerCase(),
							password: value.password,
							fetchOptions: {
								onSuccess: () => {
									navigate({ to: redirectPath ?? "/" });
								},
							},
						})
					: await authClient.signIn.username({
							username: loginValue,
							password: value.password,
							fetchOptions: {
								onSuccess: () => {
									navigate({ to: redirectPath ?? "/" });
								},
							},
						});

				if (login.error) {
					toast.error(`${login.error?.message}`);
					return;
				}
				toast.success(`Welcome back ${login.data?.user.name}`);
				if (login.data) {
					socket.disconnect();
					socket.connect();
				}
			} catch (error) {
				console.error(error);
			}
		},
	});

	return (
		<div>
			<Card className="p-3 w-96">
				<CardHeader>
					<CardTitle>
						<div className="flex flex-row justify-center">
							<Button onClick={oauthLogin} size="lg" variant="ghost">
								<Cat />
							</Button>
							<span className="mt-2">Login to your account</span>{" "}
							<Button size="lg" variant="ghost">
								<Cat />
							</Button>
						</div>
					</CardTitle>
					<CardDescription>
						Enter your username and password below
					</CardDescription>
				</CardHeader>
				<CardContent>
					<form
						onSubmit={(e) => {
							e.preventDefault();
							form.handleSubmit();
						}}
					>
						<form.AppField name="login">
							{(field) => (
								<field.InputField
									label="Username or Email Address"
									inputType="text"
									required={rememberMe}
								/>
							)}
						</form.AppField>
						<form.AppField name="password">
							{(field) => (
								<field.InputPasswordField
									label="Password"
									required={rememberMe}
								/>
							)}
						</form.AppField>

						<div className="flex flex-row justify-between mt-3 mb-3">
							<form.AppField name="rememberMe">
								{(field) => <field.CheckboxField label="Remember me" />}
							</form.AppField>

							<Link
								to="/user/resetpassword"
								className="inline-block text-sm underline-offset-4 hover:underline"
							>
								Forgot your password?
							</Link>
						</div>

						<div className="flex justify-between mt-2 ">
							<form.AppForm>
								<form.SubmitButton>Login</form.SubmitButton>
							</form.AppForm>
						</div>
					</form>
					<div className="flex justify-center mt-2">
						Don&apos;t have an account?{" "}
						<Link to={"/user/signup"} className="underline underline-offset-4">
							Sign up
						</Link>
					</div>
				</CardContent>
			</Card>
		</div>
	);
}
