/* 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 {averageScore, groupBySession, totalExams} from "@/utils/stats";
import useUser from "@/hooks/useUser";
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 MasterCorporateDashboard from "@/dashboards/MasterCorporate";
import PaymentDue from "./(status)/PaymentDue";
import {useRouter} from "next/router";
import {PayPalScriptProvider} from "@paypal/react-paypal-js";
import {CorporateUser, MasterCorporateUser, Type, User, userTypes} from "@/interfaces/user";
import Select from "react-select";
import {USER_TYPE_LABELS} from "@/resources/user";
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import {getUserCorporate} from "@/utils/groups.be";
import {getUsers} from "@/utils/users.be";

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

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

	const linkedCorporate = (await getUserCorporate(user.id)) || null;

	return {
		props: {user, linkedCorporate},
	};
}, sessionOptions);

interface Props {
	user: User;
	linkedCorporate?: CorporateUser | MasterCorporateUser;
}

export default function Home({user: propsUser, linkedCorporate}: Props) {
	const [user, setUser] = useState(propsUser);
	const [showDiagnostics, setShowDiagnostics] = useState(false);
	const [showDemographicInput, setShowDemographicInput] = useState(false);
	const [selectedScreen, setSelectedScreen] = useState<Type>("admin");

	const {mutateUser} = useUser({redirectTo: "/login"});
	const router = useRouter();

	useEffect(() => {
		if (user) {
			// setShowDemographicInput(!user.demographicInformation || !user.demographicInformation.country || !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 hasExpired user={user} reload={router.reload} />}
			</>
		);
	}

	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={(user) => {
							setUser(user);
							mutateUser(user);
						}}
						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}>
					{checkAccess(user, ["student"]) && <StudentDashboard linkedCorporate={linkedCorporate} user={user} />}
					{checkAccess(user, ["teacher"]) && <TeacherDashboard linkedCorporate={linkedCorporate} user={user} />}
					{checkAccess(user, ["corporate"]) && <CorporateDashboard linkedCorporate={linkedCorporate} user={user as CorporateUser} />}
					{checkAccess(user, ["mastercorporate"]) && <MasterCorporateDashboard user={user as MasterCorporateUser} />}
					{checkAccess(user, ["agent"]) && <AgentDashboard user={user} />}
					{checkAccess(user, ["admin"]) && <AdminDashboard user={user} />}
					{checkAccess(user, ["developer"]) && (
						<>
							<Select
								options={userTypes.map((u) => ({
									value: u,
									label: USER_TYPE_LABELS[u],
								}))}
								value={{
									value: selectedScreen,
									label: USER_TYPE_LABELS[selectedScreen],
								}}
								onChange={(value) => (value ? setSelectedScreen(value.value) : setSelectedScreen("admin"))}
							/>

							{selectedScreen === "student" && <StudentDashboard linkedCorporate={linkedCorporate} user={user} />}
							{selectedScreen === "teacher" && <TeacherDashboard linkedCorporate={linkedCorporate} user={user} />}
							{selectedScreen === "corporate" && (
								<CorporateDashboard linkedCorporate={linkedCorporate} user={user as unknown as CorporateUser} />
							)}
							{selectedScreen === "mastercorporate" && <MasterCorporateDashboard user={user as unknown as MasterCorporateUser} />}
							{selectedScreen === "agent" && <AgentDashboard user={user} />}
							{selectedScreen === "admin" && <AdminDashboard user={user} />}
						</>
					)}
				</Layout>
			)}
		</>
	);
}
