/* eslint-disable @next/next/no-img-element */
import {User} from "@/interfaces/user";
import {toast, ToastContainer} from "react-toastify";
import axios from "axios";
import {FormEvent, useEffect, useState} from "react";
import Head from "next/head";
import useUser from "@/hooks/useUser";
import {Divider} from "primereact/divider";
import Button from "@/components/Low/Button";
import {BsArrowRepeat, BsCheck} from "react-icons/bs";
import Link from "next/link";
import Input from "@/components/Low/Input";
import clsx from "clsx";
import {useRouter} from "next/router";
import EmailVerification from "./(auth)/EmailVerification";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import { requestUser } from "@/utils/api";
import { redirect } from "@/utils";

const EMAIL_REGEX = new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/g);

export const getServerSideProps = withIronSessionSsr(async ({req, res, query}) => {
	const destination = !query.destination ? "/" : Buffer.from(query.destination as string, 'base64').toString()
	const user = await requestUser(req, res)
	if (user) return redirect(destination)

	return {
		props: {user: null, destination},
	};
}, sessionOptions);

export default function Login({ destination }: { destination: string }) {
	const [email, setEmail] = useState("");
	const [password, setPassword] = useState("");
	const [rememberPassword, setRememberPassword] = useState(false);
	const [isLoading, setIsLoading] = useState(false);

	const router = useRouter();

	const {user, mutateUser} = useUser({
		redirectTo: destination,
		redirectIfFound: true,
	});

	useEffect(() => {
		if (user) router.push(destination);
	}, [router, user, destination]);

	const forgotPassword = () => {
		if (!email || email.length < 0 || !EMAIL_REGEX.test(email)) {
			toast.error("Please enter your e-mail to reset your password!", {
				toastId: "forgot-invalid-email",
			});
			return;
		}

		axios
			.post<{ok: boolean}>("/api/reset", {email})
			.then((response) => {
				if (response.data.ok) {
					toast.success("You should receive an e-mail to reset your password!", {toastId: "forgot-success"});
					return;
				}

				toast.error("That e-mail address is not connected to an account!", {
					toastId: "forgot-error",
				});
			})
			.catch(() =>
				toast.error("That e-mail address is not connected to an account!", {
					toastId: "forgot-error",
				}),
			);
	};

	const login = (e: FormEvent<HTMLFormElement>) => {
		e.preventDefault();

		setIsLoading(true);
		axios
			.post<User>("/api/login", {email, password})
			.then((response) => {
				toast.success("You have been logged in!", {
					toastId: "login-successful",
				});
				mutateUser(response.data);
			})
			.catch((e) => {
				if (e.response.status === 401) {
					toast.error("Wrong login credentials!", {
						toastId: "wrong-credentials",
					});
				} else {
					toast.error("Something went wrong!", {toastId: "server-error"});
				}
				setIsLoading(false);
			})
			.finally(() => setIsLoading(false));
	};

	return (
		<>
			<Head>
				<title>Login | EnCoach</title>
				<meta name="description" content="Generated by create next app" />
				<meta name="viewport" content="width=device-width, initial-scale=1" />
				<link rel="icon" href="/favicon.ico" />
			</Head>
			<main className="flex h-[100vh] w-full bg-white text-black">
				<ToastContainer />
				<section className="relative hidden h-full w-fit min-w-fit lg:flex">
					{/* <div className="bg-mti-rose-light absolute z-10 h-full w-full bg-opacity-50" /> */}
					<img src="/red-stock-photo.jpg" alt="People smiling looking at a tablet" className="aspect-auto h-full" />
				</section>
				<section className="flex h-full w-full flex-col items-center justify-center gap-2">
					<div className={clsx("flex flex-col items-center", !user && "mb-4")}>
						<img src="/logo_title.png" alt="EnCoach's Logo" className="w-36 lg:w-56" />
						<h1 className="text-2xl font-bold lg:text-4xl">Login to your account</h1>
						<p className="text-mti-gray-cool self-start text-sm font-normal lg:text-base">with your registered Email Address</p>
					</div>
					<Divider className="max-w-xs lg:max-w-md" />
					{!user && (
						<>
							<form className="-lg:px-8 flex w-full flex-col items-center gap-6 lg:w-1/2" onSubmit={login}>
								<Input type="email" name="email" onChange={(e) => setEmail(e.toLowerCase())} placeholder="Enter email address" />
								<Input type="password" name="password" onChange={(e) => setPassword(e)} placeholder="Password" />
								<div className="flex w-full justify-between px-4">
									<div
										className="text-mti-gray-dim flex cursor-pointer gap-3 text-xs"
										onClick={() => setRememberPassword((prev) => !prev)}>
										<input type="checkbox" className="hidden" />
										<div
											className={clsx(
												"border-mti-purple-light flex h-4 w-4 items-center justify-center rounded-sm border bg-white",
												"transition duration-300 ease-in-out",
												rememberPassword && "!bg-mti-purple-light ",
											)}>
											<BsCheck color="white" className="h-full w-full" />
										</div>
										<span>Remember my password</span>
									</div>
									<span className="text-mti-purple-light cursor-pointer text-xs hover:underline" onClick={forgotPassword}>
										Forgot Password?
									</span>
								</div>
								<Button className="mt-8 w-full" color="purple" disabled={isLoading}>
									{!isLoading && "Login"}
									{isLoading && (
										<div className="flex items-center justify-center">
											<BsArrowRepeat className="animate-spin text-white" size={25} />
										</div>
									)}
								</Button>
							</form>
							<span className="text-mti-gray-cool mt-8 text-sm font-normal">
								Don&apos;t have an account?{" "}
								<Link className="text-mti-purple-light" href="/register">
									Sign up
								</Link>
							</span>
						</>
					)}
					{/* {user && !user.isVerified && <EmailVerification user={user} isLoading={isLoading} setIsLoading={setIsLoading} />} */}
				</section>
			</main>
		</>
	);
}
