import Typography, { ITypo, ITypoColor } from "@Front/Components/DesignSystem/Typography";
import classes from "./classes.module.scss";
import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate";
import Button, { EButtonVariant } from "@Front/Components/DesignSystem/Button";
import { useCallback, useEffect, useState } from "react";
import Confirm from "@Front/Components/DesignSystem/Modal/Confirm";
import useOpenable from "@Front/Hooks/useOpenable";
import MessageBox from "@Front/Components/Elements/MessageBox";
import Link from "next/link";
import Module from "@Front/Config/Module";
import Subscriptions from "@Front/Api/LeCoffreApi/Admin/Subscriptions/Subscriptions";
import JwtService from "@Front/Services/JwtService/JwtService";
import Stripe from "@Front/Api/LeCoffreApi/Admin/Stripe/Stripe";
import { useRouter } from "next/router";
import { Subscription } from "le-coffre-resources/dist/Admin";

export enum EForfeitType {
	"standard",
	"unlimited",
}

export const forfeitsPrices: Record<EForfeitType, number> = {
	[EForfeitType.standard]: 99,
	[EForfeitType.unlimited]: 249,
};
export default function SubscriptionFacturation() {
	const router = useRouter();
	const [subscription, setSubscription] = useState<Subscription | null>(null);

	const { close: closeCancelSubscription, isOpen: isCancelSubscriptionOpen } = useOpenable();
	const { close: closeConfirmation, isOpen: isConfirmationOpen } = useOpenable();

	// const cancelSubscription = useCallback(() => {
	// 	closeCancelSubscription();
	// 	openConfirmation();
	// 	return;
	// }, [closeCancelSubscription, openConfirmation]);

	const manageSubscription = async () => {
		try {
			const jwt = JwtService.getInstance().decodeJwt();
			const subscription = await Subscriptions.getInstance().get({ where: { office: { uid: jwt?.office_Id } } });
			if (!subscription[0]) return;
			const stripe_client_portal = await Stripe.getInstance().getClientPortalSession(subscription[0].stripe_subscription_id!);
			router.push(stripe_client_portal.url + "/subscriptions/" + subscription[0].stripe_subscription_id + "/update");
		} catch (error) {}
	};

	const cancelSubscription = async () => {
		try {
			const jwt = JwtService.getInstance().decodeJwt();
			const subscription = await Subscriptions.getInstance().get({ where: { office: { uid: jwt?.office_Id } } });
			if (!subscription[0]) return;
			const stripe_client_portal = await Stripe.getInstance().getClientPortalSession(subscription[0].stripe_subscription_id!);
			router.push(stripe_client_portal.url + "/subscriptions/" + subscription[0].stripe_subscription_id + "/cancel");
		} catch (error) {}
	};

	const manageBilling = async () => {
		try {
			const jwt = JwtService.getInstance().decodeJwt();
			const subscription = await Subscriptions.getInstance().get({ where: { office: { uid: jwt?.office_Id } } });
			if (!subscription[0]) return;
			const stripe_client_portal = await Stripe.getInstance().getClientPortalSession(subscription[0].stripe_subscription_id!);
			router.push(stripe_client_portal.url);
		} catch (error) {}
	};

	const loadSubscription = useCallback(async () => {
		const jwt = JwtService.getInstance().decodeJwt();
		const subscription = await Subscriptions.getInstance().get({ where: { office: { uid: jwt?.office_Id } } });
		if (!subscription[0]) {
			router.push(Module.getInstance().get().modules.pages.Subscription.pages.New.props.path);
		} else {
			setSubscription(subscription[0]);
		}
	}, [router]);

	useEffect(() => {
		loadSubscription();
	}, [loadSubscription]);

	console.log(forfeitsPrices[EForfeitType.unlimited].toString());
	return (
		<DefaultTemplate title="Nouvelle souscription">
			{subscription && (
				<div className={classes["root"]}>
					<div className={classes["top-container"]}>
						<div className={classes["top-container-title"]}>
							<Typography typo={ITypo.H1} color={ITypoColor.BLACK}>
								Abonnement
							</Typography>
						</div>
						<div className={classes["sub-title"]}>
							<Typography typo={ITypo.P_16} color={ITypoColor.BLACK}>
								Nos forfaits sont adaptés à la taille de votre office
							</Typography>
						</div>
					</div>
					<div className={classes["forfeits-container"]}>
						<div
							className={classes["forfeit-block"]}
							data-inactive={subscription.type === "STANDARD" ? EForfeitType.standard : EForfeitType.unlimited}>
							<div className={classes["forfeit-header"]}>
								<div className={classes["left"]}>
									<Typography typo={ITypo.P_SB_18} color={ITypoColor.BLACK}>
										Forfait standard
									</Typography>
									<Typography typo={ITypo.P_16} color={ITypoColor.PINK_FLASH}>
										Plan par utilisateur
									</Typography>
								</div>
								{subscription.type === "STANDARD" && (
									<div className={classes["active-plan"]}>
										<Typography typo={ITypo.P_18} color={ITypoColor.GREEN_FLASH}>
											Plan actif
										</Typography>
									</div>
								)}
							</div>
							<div className={classes["separator"]} />
							<div className={classes["price-container"]}>
								<Typography typo={ITypo.H1} color={ITypoColor.BLACK}>
									99€
									<Typography typo={ITypo.H2} color={ITypoColor.BLACK}>
										&nbsp;HT&nbsp;
									</Typography>
									/ mois
								</Typography>
								<Typography typo={ITypo.P_18} color={ITypoColor.BLACK}>
									+ 6,99€ / collaborateur / mois
								</Typography>
							</div>
							<div className={classes["button-container"]}>
								{subscription.type === "UNLIMITED" && (
									// <Link
									// 	href={Module.getInstance().get().modules.pages.Subscription.pages.Manage.pages.Standard.props.path}>
									<Button onClick={manageSubscription} fullwidth variant={EButtonVariant.GHOST}>
										Rétrograder mon abonnement
									</Button>
									// </Link>
								)}
								{subscription.type === "STANDARD" && (
									<>
										{/* <Link
											href={
												Module.getInstance().get().modules.pages.Subscription.pages.Manage.pages.Standard.props.path
											}> */}
										<Button onClick={manageBilling} fullwidth variant={EButtonVariant.PRIMARY}>
											Gérer mon abonnement
										</Button>
										{/* </Link> */}
										<Link
											href={
												Module.getInstance().get().modules.pages.Subscription.pages.ManageCollaborators.props.path
											}>
											<Button fullwidth variant={EButtonVariant.GHOST}>
												Ajouter des collaborateurs
											</Button>
										</Link>
									</>
								)}
							</div>
						</div>
						<div
							className={classes["forfeit-block"]}
							data-inactive={subscription.type === "STANDARD" ? EForfeitType.standard : EForfeitType.unlimited}>
							<div className={classes["forfeit-header"]}>
								<div className={classes["left"]}>
									<Typography typo={ITypo.P_SB_18} color={ITypoColor.BLACK}>
										Forfait illimité
									</Typography>
									<Typography typo={ITypo.P_16} color={ITypoColor.PINK_FLASH}>
										Plan par office
									</Typography>
								</div>
								{subscription.type === "UNLIMITED" && (
									<div className={classes["active-plan"]}>
										<Typography typo={ITypo.P_18} color={ITypoColor.GREEN_FLASH}>
											Plan actif
										</Typography>
									</div>
								)}
							</div>
							<div className={classes["separator"]} />
							<div className={classes["price-container"]}>
								<Typography typo={ITypo.H1} color={ITypoColor.BLACK}>
									{/* forfeitsPrices[EForfeitType.unlimited].toString() */}€
									<Typography typo={ITypo.H2} color={ITypoColor.BLACK}>
										&nbsp;HT&nbsp;
									</Typography>
									/ mois
								</Typography>
								<Typography typo={ITypo.P_18} color={ITypoColor.BLACK}>
									Sans limite de collaborateurs
								</Typography>
							</div>
							<div className={classes["button-container"]}>
								{subscription.type === "UNLIMITED" && (
									<Button fullwidth variant={EButtonVariant.PRIMARY} disabled>
										Abonnement Max Activé
									</Button>
								)}
								{subscription.type === "STANDARD" && (
									// <Link
									// 	href={Module.getInstance().get().modules.pages.Subscription.pages.Manage.pages.Illimity.props.path}>
									<Button onClick={manageSubscription} fullwidth variant={EButtonVariant.GHOST}>
										Améliorer mon abonnement
									</Button>
									// </Link>
								)}
							</div>
						</div>
					</div>
					<div className={classes["actions-container"]}>
						<Button variant={EButtonVariant.LINE} onClick={cancelSubscription}>
							<Typography typo={ITypo.P_18} color={ITypoColor.RED_FLASH}>
								Arrêter l'abonnement
							</Typography>
						</Button>
						<Button onClick={manageBilling}>Gérer la facturation</Button>
					</div>
				</div>
			)}
			<Confirm
				isOpen={isCancelSubscriptionOpen}
				onClose={closeCancelSubscription}
				onAccept={cancelSubscription}
				closeBtn
				header={"Êtes-vous sûr de vouloir arrêter votre abonnement ?"}
				confirmText={"Confirmer"}
				cancelText={"Annuler"}>
				<div className={classes["modal-content"]}>
					<Typography typo={ITypo.P_16} className={classes["text"]}>
						Avant de confirmer, veuillez prendre note des conséquences <br />
						suivantes :
						<br />
						<ul>
							<li>
								Arrêt des fonctionnalités : Vous n'aurez plus accès aux outils de traitement et de mise à jour en temps
								réel.
							</li>
							<li>
								Accès limité : Vous pourrez uniquement télécharger vos documents existants, sans possibilité de les éditer
								ou de créer de nouveaux fichiers.
							</li>
						</ul>
						Votre abonnement se terminera le XX/XX/XXXX. Assurez-vous de sauvegarder tout ce dont vous avez besoin avant cette
						date.
					</Typography>
				</div>
			</Confirm>

			<Confirm
				isOpen={isConfirmationOpen}
				onClose={closeConfirmation}
				onAccept={closeConfirmation}
				closeBtn
				header={"Abonnement résilié avec succès"}
				confirmText={"Retour à la plateforme"}
				showCancelButton={false}>
				<div className={classes["modal-content"]}>
					<MessageBox type="info">
						Votre abonnement se terminera le XX/XX/XXXX. Assurez-vous de sauvegarder tout ce dont vous avez besoin avant cette
						date.
					</MessageBox>
				</div>
			</Confirm>
		</DefaultTemplate>
	);
}
