/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import Navbar from "@/components/Navbar";
import {BsFileEarmarkText, BsPencil, BsStar, BsBook, BsHeadphones, BsPen, BsMegaphone} from "react-icons/bs";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {useEffect, useState} from "react";
import useStats from "@/hooks/useStats";
import {averageScore, totalExams} from "@/utils/stats";
import useUser from "@/hooks/useUser";
import Sidebar from "@/components/Sidebar";
import Diagnostic from "@/components/Diagnostic";
import {ToastContainer} from "react-toastify";
import {capitalize} from "lodash";
import {Module} from "@/interfaces";
import ProgressBar from "@/components/Low/ProgressBar";
import Layout from "@/components/High/Layout";
import {calculateAverageLevel} from "@/utils/score";
import axios from "axios";
import DemographicInformationInput from "@/components/DemographicInformationInput";
import moment from "moment";
import Link from "next/link";
import {MODULE_ARRAY} from "@/utils/moduleUtils";

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

	if (!user || !user.isVerified) {
		res.setHeader("location", "/login");
		res.statusCode = 302;
		res.end();
		return {
			props: {
				user: null,
			},
		};
	}

	return {
		props: {user: req.session.user},
	};
}, sessionOptions);

export default function Home() {
	const [showDiagnostics, setShowDiagnostics] = useState(false);
	const [showDemographicInput, setShowDemographicInput] = useState(false);
	const {user, mutateUser} = useUser({redirectTo: "/login"});
	const {stats} = useStats(user?.id);

	useEffect(() => {
		if (user) {
			setShowDemographicInput(!user.demographicInformation);
			setShowDiagnostics(user.isFirstLogin);
		}
	}, [user]);

	const checkIfUserExpired = () => {
		const expirationDate = user!.subscriptionExpirationDate;

		if (expirationDate === null || expirationDate === undefined) return false;
		if (moment(expirationDate).isAfter(moment(new Date()))) return false;

		return true;
	};

	if (user && (user.isDisabled || checkIfUserExpired())) {
		return (
			<>
				<Head>
					<title>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>
				<Layout user={user} navDisabled>
					<div className="flex flex-col items-center justify-center text-center w-full gap-4">
						{user.isDisabled ? (
							<>
								<span className="font-bold text-lg">Your account has been disabled!</span>
								<span>Please contact an administrator if you believe this to be a mistake.</span>
							</>
						) : (
							<>
								<span className="font-bold text-lg">Your subscription has expired!</span>
								<div className="flex flex-col items-center">
									<span>
										Please purchase a new time pack{" "}
										<Link
											className="font-bold text-mti-purple-light underline hover:text-mti-purple-dark transition ease-in-out duration-300"
											href="https://encoach.com/join">
											here
										</Link>
										.
									</span>
									<span className="max-w-md">
										If you are not the one in charge of your subscription, please contact the one responsible to extend it.
									</span>
								</div>
							</>
						)}
					</div>
				</Layout>
			</>
		);
	}

	if (user && showDemographicInput) {
		return (
			<>
				<Head>
					<title>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>
				<Layout user={user} navDisabled>
					<DemographicInformationInput mutateUser={mutateUser} />
				</Layout>
			</>
		);
	}

	if (user && showDiagnostics) {
		return (
			<>
				<Head>
					<title>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>
				<Layout user={user} navDisabled>
					<Diagnostic user={user} onFinish={() => setShowDiagnostics(false)} />
				</Layout>
			</>
		);
	}

	return (
		<>
			<Head>
				<title>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 && (
				<Layout user={user}>
					<section className="w-full flex -md:flex-col gap-4 md:gap-8">
						<img
							src={user.profilePicture}
							alt={user.name}
							className="aspect-square h-20 md:h-64 rounded-3xl drop-shadow-xl object-cover -md:hidden"
						/>
						<div className="flex md:flex-col gap-4 md:py-4 w-full -md:items-center">
							<img
								src={user.profilePicture}
								alt={user.name}
								className="aspect-square h-24 md:hidden rounded-3xl drop-shadow-xl object-cover"
							/>
							<div className="flex -md:flex-col justify-between w-full gap-8">
								<div className="flex flex-col gap-2 py-2">
									<h1 className="font-bold text-2xl md:text-4xl">{user.name}</h1>
									<h6 className="font-normal text-base text-mti-gray-taupe">{capitalize(user.type)}</h6>
								</div>
								<ProgressBar
									label={`Level ${calculateAverageLevel(user.levels).toFixed(1)}`}
									percentage={100}
									color="purple"
									className="max-w-xs w-32 md:self-end h-10 -md:hidden"
								/>
							</div>
							<ProgressBar
								label=""
								percentage={Math.round((calculateAverageLevel(user.levels) * 100) / calculateAverageLevel(user.desiredLevels))}
								color="red"
								className="w-full h-3 drop-shadow-lg -md:hidden"
							/>
							<div className="flex justify-between w-full mt-8 -md:hidden">
								<div className="flex gap-4 items-center">
									<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
										<BsFileEarmarkText className="w-8 h-8 text-mti-red-light" />
									</div>
									<div className="flex flex-col">
										<span className="font-bold text-xl">{totalExams(stats)}</span>
										<span className="font-normal text-base text-mti-gray-dim">Exams</span>
									</div>
								</div>
								<div className="flex gap-4 items-center">
									<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
										<BsPencil className="w-8 h-8 text-mti-red-light" />
									</div>
									<div className="flex flex-col">
										<span className="font-bold text-xl">{stats.length}</span>
										<span className="font-normal text-base text-mti-gray-dim">Exercises</span>
									</div>
								</div>
								<div className="flex gap-4 items-center">
									<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
										<BsStar className="w-8 h-8 text-mti-red-light" />
									</div>
									<div className="flex flex-col">
										<span className="font-bold text-xl">{stats.length > 0 ? averageScore(stats) : 0}%</span>
										<span className="font-normal text-base text-mti-gray-dim">Average Score</span>
									</div>
								</div>
							</div>
						</div>

						<ProgressBar
							label={`Level ${calculateAverageLevel(user.levels).toFixed(1)}`}
							percentage={Math.round((calculateAverageLevel(user.levels) * 100) / calculateAverageLevel(user.desiredLevels))}
							color="purple"
							className="w-full md:hidden h-8"
							textClassName="!text-mti-black"
						/>

						<div className="grid grid-cols-2  gap-4 w-full mt-4 md:hidden">
							<div className="flex gap-4 items-center">
								<div className="w-12 h-12 md:w-16 md:h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-lg md:rounded-xl">
									<BsFileEarmarkText className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />
								</div>
								<div className="flex flex-col">
									<span className="font-bold text-lg md:text-xl">{totalExams(stats)}</span>
									<span className="font-normal text-sm md:text-base text-mti-gray-dim">Exams</span>
								</div>
							</div>
							<div className="flex gap-4 items-center">
								<div className="w-12 h-12 md:w-16 md:h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-lg md:rounded-xl">
									<BsPencil className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />
								</div>
								<div className="flex flex-col">
									<span className="font-bold text-lg md:text-xl">{stats.length}</span>
									<span className="font-normal text-sm md:text-base text-mti-gray-dim">Exercises</span>
								</div>
							</div>
							<div className="flex gap-4 items-center col-span-2">
								<div className="w-12 h-12 md:w-16 md:h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-lg md:rounded-xl">
									<BsStar className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />
								</div>
								<div className="flex flex-col">
									<span className="font-bold text-lg md:text-xl">{stats.length > 0 ? averageScore(stats) : 0}%</span>
									<span className="font-normal text-sm md:text-base text-mti-gray-dim">Average Score</span>
								</div>
							</div>
						</div>
					</section>

					<section className="flex flex-col gap-1 md:gap-3">
						<span className="font-bold text-lg">Bio</span>
						<span className="text-mti-gray-taupe">
							{user.bio || "Your bio will appear here, you can change it by clicking on your name in the top right corner."}
						</span>
					</section>

					<section className="flex flex-col gap-3">
						<span className="font-bold text-lg">Score History</span>
						<div className="grid -md:grid-rows-4 md:grid-cols-2 gap-6">
							{MODULE_ARRAY.map((module) => (
								<div className="border border-mti-gray-anti-flash rounded-xl flex flex-col gap-2 p-4" key={module}>
									<div className="flex gap-2 md:gap-3 items-center">
										<div className="w-8 h-8 md:w-12 md:h-12 bg-mti-gray-smoke flex items-center justify-center rounded-lg md:rounded-xl">
											{module === "reading" && <BsBook className="text-ielts-reading w-4 h-4 md:w-5 md:h-5" />}
											{module === "listening" && <BsHeadphones className="text-ielts-listening w-4 h-4 md:w-5 md:h-5" />}
											{module === "writing" && <BsPencil className="text-ielts-writing w-4 h-4 md:w-5 md:h-5" />}
											{module === "speaking" && <BsMegaphone className="text-ielts-speaking w-4 h-4 md:w-5 md:h-5" />}
										</div>
										<div className="flex justify-between w-full">
											<span className="font-bold md:font-extrabold text-sm">{capitalize(module)}</span>
											<span className="text-sm font-normal text-mti-gray-dim">
												Level {user.levels[module]} / Level {user.desiredLevels[module]}
											</span>
										</div>
									</div>
									<div className="md:pl-14">
										<ProgressBar
											color={module}
											label=""
											percentage={Math.round((user.levels[module] * 100) / user.desiredLevels[module])}
											className="w-full h-2"
										/>
									</div>
								</div>
							))}
						</div>
					</section>
				</Layout>
			)}
		</>
	);
}
