import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate";
import classes from "./classes.module.scss";
import Typography, { ITypo, ITypoColor } from "@Front/Components/DesignSystem/Typography";
import MessageBox from "@Front/Components/Elements/MessageBox";
import SubscriptionClientInfos from "../Components/SubscriptionClientInfos";
import Button from "@Front/Components/DesignSystem/Button";
import Link from "next/link";
import Module from "@Front/Config/Module";
import { EForfeitType } from "../SubscriptionFacturation";
import SubscribeCheckoutTicket, { EPaymentFrequencyFront as EPaymentFrequency } from "../Components/SubscribeCheckoutTicket";
import { useCallback, useEffect, useState } from "react";
import Subscriptions from "@Front/Api/LeCoffreApi/Admin/Subscriptions/Subscriptions";
import JwtService from "@Front/Services/JwtService/JwtService";
import { Subscription } from "le-coffre-resources/dist/Admin";
import Stripe from "@Front/Api/LeCoffreApi/Admin/Stripe/Stripe";
import CookieService from "@Front/Services/CookieService/CookieService";

export default function SubscriptionSuccess() {
	const [subscription, setSubscription] = useState<Subscription | null>(null);
	const [customer, setCustomer] = useState<any | null>(null);

	const loadSubscription = useCallback(async () => {
		const jwt = JwtService.getInstance().decodeJwt();
		const subscription = await Subscriptions.getInstance().get({ where: { office: { uid: jwt?.office_Id } } });
		if (!subscription[0]) return;
		setSubscription(subscription[0]);
		const customer = await Stripe.getInstance().getCustomerBySubscriptionId(subscription[0].stripe_subscription_id!);
		setCustomer(customer);
	}, []);

	const refreshToken = useCallback(async () => {
		CookieService.getInstance().deleteCookie("leCoffreAccessToken");
		const refreshToken = CookieService.getInstance().getCookie("leCoffreRefreshToken");
		if (!refreshToken) return;
		await JwtService.getInstance().forceRefreshToken(refreshToken);
		await loadSubscription();
	}, [loadSubscription]);

	const getFrequency = useCallback(() => {
		if (!subscription) return;
		const start = new Date(subscription.start_date);
		const end = new Date(subscription.end_date);

		const diffTime = Math.abs(end.getTime() - start.getTime());
		const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
		return diffDays >= 365 ? EPaymentFrequency.yearly : EPaymentFrequency.monthly;
	}, [subscription]);

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

	return (
		<DefaultTemplate title="Abonnement réussi">
			{subscription && customer && (
				<div className={classes["root"]}>
					<div className={classes["left"]}>
						<div className={classes["title"]}>
							<Typography typo={ITypo.H1} color={ITypoColor.BLACK}>
								Abonnement réussi !
							</Typography>
						</div>
						<div className={classes["alert"]}>
							<MessageBox type={"success"}>
								Votre transaction a été effectuée avec succès !
								<br />
								<br />
								Votre abonnement a été pris en compte et est désormais actif.
							</MessageBox>
						</div>
						<div className={classes["separator"]} />
						<div className={classes["client-infos"]}>
							<SubscriptionClientInfos customer={customer} />
						</div>
						<div className={classes["separator"]} />
						{subscription.type === "STANDARD" && (
							<Link
								href={
									Module.getInstance().get().modules.pages.Subscription.pages.Invite.props.path +
									`?nbOfCollaborators=${subscription.nb_seats ?? 0}`
								}>
								<Button>Inviter vos collaborateurs</Button>
							</Link>
						)}
						{subscription.type === "UNLIMITED" && (
							<Link href={Module.getInstance().get().modules.pages.Subscription.pages.Invite.props.path}>
								<Button>Inviter vos collaborateurs</Button>
							</Link>
						)}
					</div>
					<div className={classes["right"]}>
						<SubscribeCheckoutTicket
							forfeitType={subscription.type === "STANDARD" ? EForfeitType.standard : EForfeitType.unlimited}
							numberOfCollaborators={subscription.nb_seats ?? 0}
							disableInputs
							defaultFrequency={getFrequency()}
						/>
					</div>
				</div>
			)}
		</DefaultTemplate>
	);
}
