/* eslint-disable @next/next/no-img-element */
import {toast, ToastContainer} from "react-toastify";
import {useState} from "react";
import Head from "next/head";
import useUser from "@/hooks/useUser";
import Button from "@/components/Low/Button";
import {BsArrowRepeat} from "react-icons/bs";
import Link from "next/link";
import Input from "@/components/Low/Input";
import axios from "axios";
import {Divider} from "primereact/divider";
import {useRouter} from "next/router";
import clsx from "clsx";
import {EmploymentStatus, EMPLOYMENT_STATUS, Gender} from "@/interfaces/user";
import countryCodes from "country-codes-list";
import {RadioGroup} from "@headlessui/react";

export default function Register() {
	const [name, setName] = useState("");
	const [email, setEmail] = useState("");
	const [password, setPassword] = useState("");
	const [confirmPassword, setConfirmPassword] = useState("");

	const [country, setCountry] = useState<string>();
	const [phone, setPhone] = useState<string>();
	const [gender, setGender] = useState<Gender>();
	const [employment, setEmployment] = useState<EmploymentStatus>();

	const [step, setStep] = useState<0 | 1>(0);
	const [isLoading, setIsLoading] = useState(false);

	const router = useRouter();

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

	const register = (e: any) => {
		e.preventDefault();

		if (confirmPassword !== password) {
			toast.error("Your passwords do not match!", {toastId: "password-not-match"});
			setStep(0);
			return;
		}

		setIsLoading(true);
		axios
			.post("/api/register", {
				name,
				email,
				password,
				profilePicture: "/defaultAvatar.png",
				demographicInformation: {
					country,
					phone,
					gender,
					employment,
				},
			})
			.then((response) => {
				mutateUser(response.data.user).then(sendEmailVerification);
			})
			.catch((error) => {
				console.log(error.response.data);

				if (error.response.status === 401) {
					toast.error("There is already a user with that e-mail!");
					setStep(0);
					return;
				}
				toast.error("There was something wrong, please try again!");
			})
			.finally(() => setIsLoading(false));
	};

	const sendEmailVerification = () => {
		setIsLoading(true);
		axios
			.post<{ok: boolean}>("/api/reset/sendVerification", {})
			.catch((e) => {
				console.log(e);
				toast.error("Something went wrong, please logout and re-login.", {toastId: "send-verify-error"});
			})
			.finally(() => setIsLoading(false));
	};

	const logout = async () => {
		axios.post("/api/logout").finally(() => {
			setTimeout(() => router.reload(), 500);
		});
	};

	const initialStep = () => (
		<>
			<form
				className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2"
				onSubmit={(e) => {
					e.preventDefault();
					setStep(1);
				}}>
				<Input type="text" name="name" onChange={(e) => setName(e)} placeholder="Enter your name" defaultValue={name} required />
				<Input type="email" name="email" onChange={(e) => setEmail(e)} placeholder="Enter email address" defaultValue={email} required />
				<Input
					type="password"
					name="password"
					onChange={(e) => setPassword(e)}
					placeholder="Enter your password"
					defaultValue={password}
					required
				/>
				<Input
					type="password"
					name="confirmPassword"
					onChange={(e) => setConfirmPassword(e)}
					placeholder="Confirm your password"
					defaultValue={confirmPassword}
					required
				/>
				<Button
					className="lg:mt-8 w-full"
					color="purple"
					disabled={isLoading || !email || !name || !password || !confirmPassword || password !== confirmPassword}>
					Next
				</Button>
			</form>
		</>
	);

	const demographicStep = () => (
		<>
			<form className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2" onSubmit={register}>
				<div className="relative flex flex-col gap-3 w-full">
					<label className="font-normal text-base text-mti-gray-dim">Country *</label>
					<select
						name="country"
						className="px-8 py-6 text-sm font-normal placeholder:text-mti-gray-cool bg-white rounded-full border border-mti-gray-platinum focus:outline-none"
						onChange={(e) => {
							setCountry(e.target.value);
						}}
						defaultValue={country}>
						<option value={undefined} disabled selected>
							Select a country
						</option>
						{countryCodes.all().map((x) => (
							<option key={x.countryCode} value={x.countryCode}>
								{x.flag} {x.countryNameLocal}
							</option>
						))}
					</select>
				</div>
				<Input
					type="tel"
					name="phone"
					label="Phone number"
					onChange={(e) => setPhone(e)}
					placeholder="Enter phone number"
					defaultValue={phone}
					required
				/>
				<div className="relative flex flex-col gap-3 w-full">
					<label className="font-normal text-base text-mti-gray-dim">Gender *</label>
					<RadioGroup value={gender} onChange={setGender} className="flex flex-row justify-between">
						<RadioGroup.Option value="male">
							{({checked}) => (
								<span
									className={clsx(
										"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
										"transition duration-300 ease-in-out",
										!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
									)}>
									Male
								</span>
							)}
						</RadioGroup.Option>
						<RadioGroup.Option value="female">
							{({checked}) => (
								<span
									className={clsx(
										"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
										"transition duration-300 ease-in-out",
										!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
									)}>
									Female
								</span>
							)}
						</RadioGroup.Option>
						<RadioGroup.Option value="other">
							{({checked}) => (
								<span
									className={clsx(
										"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
										"transition duration-300 ease-in-out",
										!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
									)}>
									Other
								</span>
							)}
						</RadioGroup.Option>
					</RadioGroup>
				</div>
				<div className="relative flex flex-col gap-3 w-full">
					<label className="font-normal text-base text-mti-gray-dim">Employment Status *</label>
					<RadioGroup value={employment} onChange={setEmployment} className="grid grid-cols-2 items-center gap-4 place-items-center">
						{EMPLOYMENT_STATUS.map(({status, label}) => (
							<RadioGroup.Option value={status} key={status}>
								{({checked}) => (
									<span
										className={clsx(
											"px-6 py-4 w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
											"transition duration-300 ease-in-out",
											!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
										)}>
										{label}
									</span>
								)}
							</RadioGroup.Option>
						))}
					</RadioGroup>
				</div>

				<Button className="lg:mt-8 w-full" color="purple" disabled={isLoading || !country || !phone || !gender || !employment}>
					{!isLoading && "Create account"}
					{isLoading && (
						<div className="flex items-center justify-center">
							<BsArrowRepeat className="text-white animate-spin" size={25} />
						</div>
					)}
				</Button>
				<Button className="w-full" color="purple" variant="outline" type="button" onClick={() => setStep(0)} disabled={isLoading}>
					Back
				</Button>
			</form>
		</>
	);

	return (
		<>
			<Head>
				<title>Register | 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="w-full h-[100vh] flex bg-white text-black">
				<ToastContainer />
				<section className="h-full w-fit min-w-fit relative hidden lg:flex">
					<div className="absolute h-full w-full bg-mti-rose-light z-10 bg-opacity-50" />
					<img src="/people-talking-tablet.png" alt="People smiling looking at a tablet" className="h-full aspect-auto" />
				</section>
				<section className="h-full w-full flex flex-col items-center justify-center gap-4">
					<div className={clsx("flex flex-col gap-2 items-center relative", !user && "mb-4")}>
						<img src="/logo_title.png" alt="EnCoach's Logo" className="w-36 lg:w-64 absolute -top-36 lg:-top-64" />
						<h1 className="font-bold text-2xl lg:text-4xl">{step === 1 ? "Demographic Information" : "Create new account"}</h1>
					</div>
					{!user && (
						<>
							{step === 0 && initialStep()}
							{step === 1 && demographicStep()}
							<Link className="text-mti-purple-light text-sm font-normal" href="/login">
								Sign in instead
							</Link>
						</>
					)}
					{user && !user.isVerified && (
						<>
							<Divider className="max-w-xs lg:max-w-md" />
							<div className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2 relative">
								<h4 className="font-semibold text-2xl text-mti-purple-light">Please confirm your account!</h4>
								<span className="text-center">
									An e-mail has been sent to <span className="italic text-mti-purple-light">{user.email}</span>, please click the
									link in it to confirm your account to be able to use the application. <br /> <br />
									Please refresh this page once it has been verified.
								</span>
								<Button className="mt-8 w-full" color="purple" disabled={isLoading} onClick={sendEmailVerification}>
									Resend e-mail
								</Button>
							</div>
							<Divider className="max-w-xs lg:max-w-md" />
							<span className="text-mti-gray-cool text-sm font-normal">
								<button className="text-mti-purple-light" onClick={logout}>
									Log out instead
								</button>
							</span>
						</>
					)}
				</section>
			</main>
		</>
	);
}
