/* 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, groupBySession, 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";
import ProfileSummary from "@/components/ProfileSummary";
import StudentDashboard from "@/dashboards/Student";
import AdminDashboard from "@/dashboards/Admin";
import CorporateDashboard from "@/dashboards/Corporate";
import TeacherDashboard from "@/dashboards/Teacher";
import AgentDashboard from "@/dashboards/Agent";
import PaymentDue from "./(status)/PaymentDue";
import {useRouter} from "next/router";
import {PayPalScriptProvider} from "@paypal/react-paypal-js";

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

	const envVariables: {[key: string]: string} = {};
	Object.keys(process.env)
		.filter((x) => x.startsWith("NEXT_PUBLIC"))
		.forEach((x: string) => {
			envVariables[x] = process.env[x]!;
		});

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

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

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

	useEffect(() => {
		if (user) {
			setShowDemographicInput(
				!user.demographicInformation ||
					!user.demographicInformation.country ||
					!user.demographicInformation.gender ||
					!user.demographicInformation.phone,
			);
			setShowDiagnostics(user.isFirstLogin && user.type === "student");
		}
	}, [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.status === "paymentDue" || user.status === "disabled" || 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>
				{user.status === "disabled" && (
					<Layout user={user} navDisabled>
						<div className="flex flex-col items-center justify-center text-center w-full gap-4">
							<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>
						</div>
					</Layout>
				)}
				{(user.status === "paymentDue" || checkIfUserExpired()) && (
					<PaymentDue
						key={envVariables["NEXT_PUBLIC_PAYPAL_CLIENT_ID"]}
						hasExpired
						user={user}
						reload={router.reload}
						clientID={envVariables["NEXT_PUBLIC_PAYPAL_CLIENT_ID"] || ""}
					/>
				)}
			</>
		);
	}

	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} user={user} />
				</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}>
					{user.type === "student" && <StudentDashboard user={user} />}
					{user.type === "teacher" && <TeacherDashboard user={user} />}
					{user.type === "corporate" && <CorporateDashboard user={user} />}
					{user.type === "agent" && <AgentDashboard user={user} />}
					{user.type === "admin" && <AdminDashboard user={user} />}
					{user.type === "developer" && <AdminDashboard user={user} />}
				</Layout>
			)}
		</>
	);
}
