/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {ChangeEvent, Dispatch, ReactNode, SetStateAction, useEffect, useRef, useState} from "react";
import useUser from "@/hooks/useUser";
import {toast, ToastContainer} from "react-toastify";
import Layout from "@/components/High/Layout";
import Input from "@/components/Low/Input";
import Button from "@/components/Low/Button";
import Link from "next/link";
import axios from "axios";
import {ErrorMessage} from "@/constants/errors";
import clsx from "clsx";
import {
	CorporateUser,
	EmploymentStatus,
	EMPLOYMENT_STATUS,
	Gender,
	User,
	DemographicInformation,
	MasterCorporateUser,
	Group,
} from "@/interfaces/user";
import CountrySelect from "@/components/Low/CountrySelect";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import moment from "moment";
import {BsCamera, BsQuestionCircleFill} from "react-icons/bs";
import {USER_TYPE_LABELS} from "@/resources/user";
import useGroups from "@/hooks/useGroups";
import useUsers from "@/hooks/useUsers";
import {convertBase64} from "@/utils";
import {Divider} from "primereact/divider";
import GenderInput from "@/components/High/GenderInput";
import EmploymentStatusInput from "@/components/High/EmploymentStatusInput";
import TimezoneSelect from "@/components/Low/TImezoneSelect";
import Modal from "@/components/Modal";
import {Module} from "@/interfaces";
import ModuleLevelSelector from "@/components/Medium/ModuleLevelSelector";
import Select from "@/components/Low/Select";
import {InstructorGender} from "@/interfaces/exam";
import {capitalize} from "lodash";
import TopicModal from "@/components/Medium/TopicModal";
import {v4} from "uuid";
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import {getParticipantGroups, getUserCorporate} from "@/utils/groups.be";
import {InferGetServerSidePropsType} from "next";
import {getUsers} from "@/utils/users.be";

export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
	const user = req.session.user;

	if (!user) {
		return {
			redirect: {
				destination: "/login",
				permanent: false,
			},
		};
	}

	if (shouldRedirectHome(user)) {
		return {
			redirect: {
				destination: "/",
				permanent: false,
			},
		};
	}

	return {
		props: {
			user,
			linkedCorporate: (await getUserCorporate(user.id)) || null,
			groups: await getParticipantGroups(user.id),
			users: await getUsers(),
		},
	};
}, sessionOptions);

interface Props {
	user: User;
	groups: Group[];
	users: User[];
	mutateUser: Function;
	linkedCorporate?: CorporateUser | MasterCorporateUser;
}

const DoubleColumnRow = ({children}: {children: ReactNode}) => <div className="flex flex-col lg:flex-row gap-8 w-full">{children}</div>;

function UserProfile({user, mutateUser, linkedCorporate, groups, users}: Props) {
	const [bio, setBio] = useState(user.bio || "");
	const [name, setName] = useState(user.name || "");
	const [email, setEmail] = useState(user.email || "");
	const [password, setPassword] = useState("");
	const [newPassword, setNewPassword] = useState("");
	const [isLoading, setIsLoading] = useState(false);
	const [profilePicture, setProfilePicture] = useState(user.profilePicture);

	const [desiredLevels, setDesiredLevels] = useState(checkAccess(user, ["developer", "student"]) ? user.desiredLevels : undefined);
	const [focus, setFocus] = useState<"academic" | "general">(user.focus);

	const [country, setCountry] = useState<string>(user.demographicInformation?.country || "");
	const [phone, setPhone] = useState<string>(user.demographicInformation?.phone || "");
	const [gender, setGender] = useState<Gender | undefined>(user.demographicInformation?.gender || undefined);
	const [employment, setEmployment] = useState<EmploymentStatus | undefined>(
		checkAccess(user, ["corporate", "mastercorporate"]) ? undefined : (user.demographicInformation as DemographicInformation)?.employment,
	);
	const [passport_id, setPassportID] = useState<string | undefined>(
		checkAccess(user, ["student"]) ? (user.demographicInformation as DemographicInformation)?.passport_id : undefined,
	);

	const [preferredGender, setPreferredGender] = useState<InstructorGender | undefined>(
		user.type === "student" || user.type === "developer" ? user.preferredGender || "varied" : undefined,
	);
	const [preferredTopics, setPreferredTopics] = useState<string[] | undefined>(
		user.type === "student" || user.type === "developer" ? user.preferredTopics : undefined,
	);

	const [position, setPosition] = useState<string | undefined>(
		user.type === "corporate" || user.type === "mastercorporate" ? user.demographicInformation?.position : undefined,
	);
	const [corporateInformation, setCorporateInformation] = useState(
		user.type === "corporate" || user.type === "mastercorporate" ? user.corporateInformation : undefined,
	);

	const [companyName] = useState<string | undefined>(user.type === "agent" ? user.agentInformation?.companyName : undefined);
	const [commercialRegistration] = useState<string | undefined>(user.type === "agent" ? user.agentInformation?.commercialRegistration : undefined);
	const [arabName, setArabName] = useState<string | undefined>(user.type === "agent" ? user.agentInformation?.companyArabName : undefined);
	const [timezone, setTimezone] = useState<string>(user.demographicInformation?.timezone || moment.tz.guess());
	const [isPreferredTopicsOpen, setIsPreferredTopicsOpen] = useState(false);

	const profilePictureInput = useRef(null);
	const expirationDateColor = (date: Date) => {
		const momentDate = moment(date);
		const today = moment(new Date());

		if (today.add(1, "days").isAfter(momentDate)) return "!bg-mti-red-ultralight border-mti-red-light";
		if (today.add(3, "days").isAfter(momentDate)) return "!bg-mti-rose-ultralight border-mti-rose-light";
		if (today.add(7, "days").isAfter(momentDate)) return "!bg-mti-orange-ultralight border-mti-orange-light";
	};

	const uploadProfilePicture = async (event: ChangeEvent<HTMLInputElement>) => {
		if (event.target.files && event.target.files[0]) {
			const picture = event.target.files[0];
			const base64 = await convertBase64(picture);
			setProfilePicture(base64 as string);
		}
	};

	const updateUser = async () => {
		setIsLoading(true);
		if (email !== user?.email && !password) {
			toast.error("To update your e-mail you need to input your password!");
			setIsLoading(false);
			return;
		}

		if (newPassword && !password) {
			toast.error("To update your password you need to input your current one!");
			setIsLoading(false);
			return;
		}

		if (email !== user?.email) {
			const userAdmins = groups.filter((x) => x.participants.includes(user.id)).map((x) => x.admin);
			const message =
				users.filter((x) => userAdmins.includes(x.id) && x.type === "corporate").length > 0
					? "If you change your e-mail address, you will lose all benefits from your university/institute. Are you sure you want to continue?"
					: "Are you sure you want to update your e-mail address?";

			if (!confirm(message)) {
				setIsLoading(false);
				return;
			}
		}

		axios
			.post("/api/users/update", {
				bio,
				name,
				email,
				password,
				newPassword,
				profilePicture,
				desiredLevels,
				preferredGender,
				preferredTopics,
				focus,
				demographicInformation: {
					phone,
					country,
					employment: user?.type === "corporate" ? undefined : employment,
					position: user?.type === "corporate" ? position : undefined,
					gender,
					passport_id,
					timezone,
				},
				...(user.type === "corporate" ? {corporateInformation} : {}),
				...(user.type === "agent"
					? {
							agentInformation: {
								companyName,
								commercialRegistration,
								arabName,
							},
					  }
					: {}),
			})
			.then((response) => {
				if (response.status === 200) {
					toast.success("Your profile has been updated!");
					mutateUser((response.data as {user: User}).user);
					setIsLoading(false);
					return;
				}
			})
			.catch((error) => {
				console.log(error);
				toast.error((error.response.data as ErrorMessage).message);
			})
			.finally(() => {
				setIsLoading(false);
			});
	};

	const ExpirationDate = () => (
		<div className="flex flex-col gap-3 w-full">
			<label className="font-normal text-base text-mti-gray-dim">Expiry Date (click to purchase)</label>
			<Link
				href="/payment"
				className={clsx(
					"p-6 w-full flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
					"transition duration-300 ease-in-out",
					!user.subscriptionExpirationDate
						? "!bg-mti-green-ultralight !border-mti-green-light"
						: expirationDateColor(user.subscriptionExpirationDate),
					"bg-white border-mti-gray-platinum",
				)}>
				{!user.subscriptionExpirationDate && "Unlimited"}
				{user.subscriptionExpirationDate && moment(user.subscriptionExpirationDate).format("DD/MM/YYYY")}
			</Link>
		</div>
	);

	const TimezoneInput = () => (
		<div className="flex flex-col gap-3 w-full">
			<label className="font-normal text-base text-mti-gray-dim">Timezone</label>
			<TimezoneSelect value={timezone} onChange={setTimezone} />
		</div>
	);

	const manualDownloadLink = ["student", "teacher", "corporate"].includes(user.type) ? `/manuals/${user.type}.pdf` : "";

	return (
		<Layout user={user}>
			<section className="w-full flex flex-col gap-4 md:gap-8 px-4 py-8">
				<h1 className="text-4xl font-bold mb-6 md:hidden">Edit Profile</h1>
				<div className="flex -md:flex-col-reverse -md:items-center w-full justify-between">
					<div className="flex flex-col gap-8 w-full md:w-2/3">
						<h1 className="text-4xl font-bold mb-6 -md:hidden">Edit Profile</h1>
						<form className="flex flex-col items-center gap-6 w-full" onSubmit={(e) => e.preventDefault()}>
							<DoubleColumnRow>
								{user.type !== "corporate" && user.type !== "mastercorporate" ? (
									<Input
										label={user.type === "agent" ? "English name" : "Name"}
										type="text"
										name="name"
										onChange={(e) => setName(e)}
										placeholder="Enter your name"
										defaultValue={name}
										required
									/>
								) : (
									<Input
										label="Company name"
										type="text"
										name="name"
										disabled={!!linkedCorporate}
										onChange={(e) =>
											setCorporateInformation((prev) => ({
												...prev!,
												companyInformation: {
													...prev!.companyInformation,
													name: e,
												},
											}))
										}
										placeholder="Enter your company's name"
										defaultValue={corporateInformation?.companyInformation?.name}
										required
									/>
								)}

								{user.type === "agent" && (
									<Input
										label="Arab name"
										type="text"
										name="arabName"
										onChange={(e) => setArabName(e)}
										placeholder="Enter your arab name"
										defaultValue={arabName}
										required
									/>
								)}

								<Input
									label="E-mail Address"
									type="email"
									name="email"
									onChange={(e) => setEmail(e)}
									placeholder="Enter email address"
									defaultValue={email}
									required
								/>
							</DoubleColumnRow>
							<DoubleColumnRow>
								<Input
									label="Current Password"
									type="password"
									name="password"
									onChange={(e) => setPassword(e)}
									placeholder="Enter your password"
									required
								/>
								<Input
									label="New Password"
									type="password"
									name="newPassword"
									onChange={(e) => setNewPassword(e)}
									placeholder="Enter your new password (optional)"
								/>
							</DoubleColumnRow>
							{user.type === "agent" && (
								<div className="grid grid-cols-1 md:grid-cols-2 gap-8 w-full">
									<Input
										label="Company Name"
										type="text"
										name="companyName"
										onChange={() => null}
										placeholder="Enter your company's name"
										defaultValue={companyName}
										disabled
									/>
									<Input
										label="Commercial Registration"
										type="text"
										name="commercialRegistration"
										onChange={() => null}
										placeholder="Enter commercial registration"
										defaultValue={commercialRegistration}
										disabled
									/>
								</div>
							)}

							<DoubleColumnRow>
								<div className="flex flex-col gap-3 w-full">
									<label className="font-normal text-base text-mti-gray-dim">Country *</label>
									<CountrySelect value={country} onChange={setCountry} />
								</div>
								<Input
									type="tel"
									name="phone"
									label="Phone number"
									onChange={(e) => setPhone(e)}
									placeholder="Enter phone number"
									defaultValue={phone}
									required
								/>
							</DoubleColumnRow>

							{user.type === "student" ? (
								<DoubleColumnRow>
									<Input
										type="text"
										name="passport_id"
										label="Passport/National ID"
										onChange={(e) => setPassportID(e)}
										placeholder="Enter National ID or Passport number"
										value={passport_id}
										required
									/>
									<TimezoneInput />
								</DoubleColumnRow>
							) : (
								<TimezoneInput />
							)}

							<Divider />

							{desiredLevels && ["developer", "student"].includes(user.type) && (
								<>
									<div className="flex flex-col gap-3 w-full">
										<label className="font-normal text-base text-mti-gray-dim">Desired Levels</label>
										<ModuleLevelSelector
											levels={desiredLevels}
											setLevels={setDesiredLevels as Dispatch<SetStateAction<{[key in Module]: number}>>}
										/>
									</div>
									<div className="flex flex-col gap-3 w-full">
										<label className="font-normal text-base text-mti-gray-dim">Focus</label>
										<div className="grid grid-cols-1 md:grid-cols-2 gap-y-4 gap-x-16 w-full">
											<button
												onClick={() => setFocus("academic")}
												className={clsx(
													"w-full border border-mti-gray-platinum rounded-full px-6 py-4 flex justify-center items-center gap-12 bg-white",
													"hover:bg-mti-purple-light hover:text-white",
													focus === "academic" && "!bg-mti-purple-light !text-white",
													"transition duration-300 ease-in-out",
												)}>
												Academic
											</button>
											<button
												onClick={() => setFocus("general")}
												className={clsx(
													"w-full border border-mti-gray-platinum rounded-full px-6 py-4 flex justify-center items-center gap-12 bg-white",
													"hover:bg-mti-purple-light hover:text-white",
													focus === "general" && "!bg-mti-purple-light !text-white",
													"transition duration-300 ease-in-out",
												)}>
												General
											</button>
										</div>
									</div>
								</>
							)}

							{preferredGender && ["developer", "student"].includes(user.type) && (
								<>
									<Divider />
									<DoubleColumnRow>
										<div className="flex flex-col gap-3 w-full">
											<label className="font-normal text-base text-mti-gray-dim">Speaking Instructor&apos;s Gender</label>
											<Select
												value={{
													value: preferredGender,
													label: capitalize(preferredGender),
												}}
												onChange={(value) => (value ? setPreferredGender(value.value as InstructorGender) : null)}
												options={[
													{value: "male", label: "Male"},
													{value: "female", label: "Female"},
													{value: "varied", label: "Varied"},
												]}
											/>
										</div>
										<div className="flex flex-col gap-4 w-full">
											<label className="font-normal text-base text-mti-gray-dim flex gap-2 items-center">
												Preferred Topics{" "}
												<span
													className="tooltip"
													data-tip="These topics will be considered for speaking and writing modules, aiming to include at least one exercise containing of the these in the selected exams.">
													<BsQuestionCircleFill />
												</span>
											</label>
											<Button className="w-full" variant="outline" onClick={() => setIsPreferredTopicsOpen(true)}>
												Select Topics ({preferredTopics?.length || "All"} selected)
											</Button>
										</div>
									</DoubleColumnRow>

									<TopicModal
										key={v4()}
										isOpen={isPreferredTopicsOpen}
										onClose={() => setIsPreferredTopicsOpen(false)}
										selectTopics={setPreferredTopics}
										initialTopics={preferredTopics || []}
									/>

									<Divider />
								</>
							)}

							{user.type === "corporate" && (
								<>
									<DoubleColumnRow>
										<Input
											type="number"
											name="companyUsers"
											onChange={() => null}
											label="Number of users"
											defaultValue={user.corporateInformation?.companyInformation.userAmount}
											disabled
											required
										/>
										<Input
											type="text"
											name="pricing"
											onChange={() => null}
											label="Pricing"
											defaultValue={`${user.corporateInformation.payment?.value} ${user.corporateInformation.payment?.currency}`}
											disabled
											required
										/>
									</DoubleColumnRow>
									<ExpirationDate />
								</>
							)}

							{user.type === "corporate" && (
								<>
									<Divider />
									<DoubleColumnRow>
										<Input
											label="Name"
											type="text"
											name="name"
											onChange={(e) => setName(e)}
											placeholder="Enter your name"
											defaultValue={name}
											required
										/>
										<Input
											name="position"
											onChange={setPosition}
											defaultValue={position}
											type="text"
											label="Department"
											placeholder="CEO, Head of Marketing..."
											required
											disabled={!!linkedCorporate}
										/>
									</DoubleColumnRow>
								</>
							)}

							{user.type === "corporate" && user.corporateInformation.referralAgent && (
								<>
									<Divider />
									<DoubleColumnRow>
										<Input
											name="agentName"
											onChange={() => null}
											defaultValue={users.find((x) => x.id === user.corporateInformation.referralAgent)?.name}
											type="text"
											label="Country Manager's Name"
											placeholder="Not available"
											required
											disabled
										/>
										<Input
											name="agentEmail"
											onChange={() => null}
											defaultValue={users.find((x) => x.id === user.corporateInformation.referralAgent)?.email}
											type="text"
											label="Country Manager's E-mail"
											placeholder="Not available"
											required
											disabled
										/>
									</DoubleColumnRow>
									<DoubleColumnRow>
										<div className="flex flex-col gap-2 w-full">
											<label className="font-normal text-base text-mti-gray-dim">Country Manager&apos;s Country *</label>
											<CountrySelect
												value={
													users.find((x) => x.id === user.corporateInformation.referralAgent)?.demographicInformation
														?.country
												}
												onChange={() => null}
												disabled
											/>
										</div>

										<Input
											type="tel"
											name="agentPhone"
											label="Country Manager's Phone"
											onChange={() => null}
											placeholder="Not available"
											defaultValue={
												users.find((x) => x.id === user.corporateInformation.referralAgent)?.demographicInformation?.phone
											}
											disabled
											required
										/>
									</DoubleColumnRow>
								</>
							)}

							{user.type !== "corporate" && (
								<DoubleColumnRow>
									<EmploymentStatusInput value={employment} onChange={setEmployment} />

									<div className="flex flex-col gap-8 w-full">
										<GenderInput value={gender} onChange={setGender} />
										<ExpirationDate />
									</div>
								</DoubleColumnRow>
							)}
						</form>
					</div>
					<div className="flex flex-col gap-6 w-48">
						<div
							className="flex flex-col gap-3 items-center h-fit cursor-pointer group"
							onClick={() => (profilePictureInput.current as any)?.click()}>
							<div className="relative overflow-hidden h-48 w-48 rounded-full">
								<div
									className={clsx(
										"absolute top-0 left-0 bg-mti-purple-light/60 w-full h-full z-20 flex items-center justify-center opacity-0 group-hover:opacity-100",
										"transition ease-in-out duration-300",
									)}>
									<BsCamera className="text-6xl text-mti-purple-ultralight/80" />
								</div>
								<img src={profilePicture} alt={user.name} className="aspect-square drop-shadow-xl self-end object-cover" />
							</div>
							<input type="file" className="hidden" onChange={uploadProfilePicture} accept="image/*" ref={profilePictureInput} />
							<span
								onClick={() => (profilePictureInput.current as any)?.click()}
								className="cursor-pointer text-mti-purple-light text-sm">
								Change picture
							</span>
							<h6 className="font-normal text-base text-mti-gray-taupe">{USER_TYPE_LABELS[user.type]}</h6>
						</div>
						{user.type === "agent" && (
							<div className="flag items-center h-fit">
								<img
									alt={user.demographicInformation?.country.toLowerCase() + "_flag"}
									src={`https://flagcdn.com/w320/${user.demographicInformation?.country.toLowerCase()}.png`}
									width="320"
								/>
							</div>
						)}
						{manualDownloadLink && (
							<a href={manualDownloadLink} className="max-w-[200px] self-end w-full" download>
								<Button color="purple" variant="outline" className="max-w-[200px] self-end w-full">
									Download Manual
								</Button>
							</a>
						)}
					</div>
				</div>
				<div className="flex flex-col gap-4 mt-8 mb-20">
					<span className="text-lg font-bold">Bio</span>
					<textarea
						className="w-full h-full min-h-[148px] cursor-text px-7 py-8 input border-2 border-mti-gray-platinum bg-white rounded-3xl"
						onChange={(e) => setBio(e.target.value)}
						defaultValue={bio}
						placeholder="Write your text here..."
					/>
				</div>

				<div className="self-end flex justify-between w-full gap-8 absolute bottom-8 left-0 px-8">
					<Link href="/" className="max-w-[200px] self-end w-full">
						<Button color="purple" variant="outline" className="max-w-[200px] self-end w-full">
							Back
						</Button>
					</Link>
					<Button color="purple" className="max-w-[200px] self-end w-full" onClick={updateUser} disabled={isLoading}>
						Save Changes
					</Button>
				</div>
			</section>
		</Layout>
	);
}

export default function Home(props: {linkedCorporate?: CorporateUser | MasterCorporateUser; groups: Group[]; users: User[]}) {
	const {user, mutateUser} = useUser({redirectTo: "/login"});

	return (
		<>
			<Head>
				<title>Profile | EnCoach</title>
				<meta
					name="description"
					content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
				/>
				<meta name="viewport" content="width=device-width, initial-scale=1" />
				<link rel="icon" href="/favicon.ico" />
			</Head>
			<ToastContainer />
			{user && <UserProfile user={user} mutateUser={mutateUser} {...props} />}
		</>
	);
}
