import LockIcon from "@mui/icons-material/Lock";
import { Chip } from "@mui/material";
import React, { useEffect, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getUserSubscriptions } from "../../../redux/authSlice";
import { getFormattedCurrency } from "../../../utils";
import style from "./CartSummaryCard.module.css";

function CartSummaryCard() {
	const dispatch = useDispatch();

	const { purchaseDetails, user, userProfile } = useSelector(
		({ purchase, auth }) => {
			return {
				purchaseDetails: purchase.purchaseDetails,
				user: auth.user,
				userProfile: auth.userProfile,
			};
		}
	);

	if (!purchaseDetails) return <></>;

	const [subscriptions, setSubscriptions] = useState();

	let data = useMemo(() => {
		const data = JSON.parse(JSON.stringify(purchaseDetails));

		data.cartItems = data.cartItems?.map((cartItem) => {
			if (cartItem.buyingOnlyLicenses)
				cartItem.chip = { label: "EXTRA LICENSES", color: "info" };
			else if (
				subscriptions &&
				subscriptions
					.filter(({ userProfileId }) => {
						if (userProfile) return userProfileId === userProfile._id;
						return true;
					})
					.map(({ plan }) => plan._id)
					.includes(cartItem.planId)
			)
				cartItem.chip = { label: "SUBSCRIPTION RENEWAL", color: "warning" };
			else cartItem.chip = { label: "NEW SUBSCRIPTION", color: "success" };

			return cartItem;
		});

		return data;
	}, [purchaseDetails, subscriptions, userProfile]);

	const loadSubscriptions = async (userId) => {
		const userPlans = await dispatch(getUserSubscriptions({ userId })).unwrap();
		if (userPlans) setSubscriptions(userPlans.subscriptions);
	};

	useEffect(() => {
		if (user) loadSubscriptions(user._id);
	}, [user]);

	return (
		<div className={style.container}>
			<div className={style.section1}>
				<p>Total Amount To Be Paid</p>
				<p>{getFormattedCurrency(data.currency, data.totalCost)}</p>
				<div className={style.line3}>
					<LockIcon color="success" /> <p>Secure Payment</p>
				</div>
			</div>
			<div className={style.section2}>
				<p style={{ fontWeight: "500", fontSize: "1.2rem" }}>Order Summary</p>
				{data &&
					data.cartItems &&
					data.cartItems.map((cartItem) => (
						<>
							<div className={style.product}>
								<Chip
									color={cartItem.chip.color}
									label={cartItem.chip.label}
									sx={{ my: 1, fontWeight: 600 }}
									size="small"
								/>
								<div className={style.row1}>
									<p>{cartItem.plan.name}</p>
									<p>{getFormattedCurrency(data.currency, cartItem.subscriptionCost)}</p>
								</div>
								<div className={style.row2}>
									<p>
										{" "}
										{cartItem.plan.variants[cartItem.planVariantIdx].termInMonths === 12
											? "ANNUAL"
											: "QUARTERLY"}{" "}
										PLAN
									</p>
									<p>
										BILLED PER{" "}
										{cartItem.plan.variants[cartItem.planVariantIdx].termInMonths === 12
											? "YEAR"
											: "QUARTER"}
									</p>
								</div>

								{cartItem.additionalLicenses &&
									cartItem.additionalLicenses.length > 0 && (
										// <div className={style.product}>
										<>
											<div className={style.row1} style={{ marginTop: "1rem" }}>
												<p>Member Access</p>
												<p>• {cartItem.additionalLicenses[0].count} Seats •</p>

												<p>
													{getFormattedCurrency(
														data.currency,
														cartItem.additionalLicenses[0].price
													)}
												</p>
											</div>

											<div className={style.row2}>
												<p style={{ marginLeft: "auto", width: "125px" }}>
													BILLED PER SEAT PER{" "}
													{cartItem.plan.variants[cartItem.planVariantIdx].termInMonths ===
													12
														? "YEAR"
														: "QUARTER"}
												</p>
											</div>
										</>
										// </div>
									)}
							</div>
						</>
					))}
			</div>
			<div className={style.section3}>
				<div>
					<p>Sub-total</p>
					<p>{getFormattedCurrency(data.currency, data.subTotalCost)}</p>
				</div>
				<div>
					<p>Other taxes</p>
					<p>{getFormattedCurrency(data.currency, data.otherTaxesCost)}</p>
				</div>

				{data.discount && (
					<>
						<div>
							<p>Discount Code</p>
							<p>{data.discount.code}</p>
						</div>
						<div>
							<p>Discount Amount</p>
							<p style={{ color: "green" }}>
								- {getFormattedCurrency(data.currency, data.discount.amount)}
							</p>
						</div>
					</>
				)}
			</div>
			<div className={style.section4}>
				<div>
					<p>Total</p>
					<p>{getFormattedCurrency(data.currency, data.totalCost)}</p>
				</div>
			</div>
		</div>
	);
}

export default CartSummaryCard;
