/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react/jsx-no-bind */
// eslint-disable-next-line object-curly-newline
import { ArrowBackIos } from '@mui/icons-material';
import { Button } from '@mui/material';
import { PayPalButtons, PayPalScriptProvider } from '@paypal/react-paypal-js';
import axios from 'axios';
import classNames from 'classnames';
import type { FormEvent } from 'react';
import type React from 'react';
import { useContext, useDeferredValue, useEffect, useReducer, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';
import globalStyle from '../../Components/GlobalStyles/globals.module.scss';

import SignInHeader from '../../Components/Layout/Header/SignInHeader';
import environment from '../../Environments/environment';
import {
	downgradeCompanyPlan,
	payAndSetCompanyPlan,
	selectCompany,
	setCompanyPlan
} from '../../ReduxState/companies/companiesSlice';
import {
	fetchFinancialsData,
	setDemoFinancials,
	setSelectedFinancials
} from '../../ReduxState/financials/financialsSlice';
import type { AppDispatch, RootState } from '../../ReduxState/store';
import { AccountContext } from '../../Store/Account/account-context';
import type { AccountContextModel } from '../../Store/Account/AccountContextModel';
import type { GlobalStateModel } from '../../Store/global/GlobalState-context';
import { GlobalStateContext } from '../../Store/global/GlobalState-context';
import type { ManageSubscriptionContextModel } from '../../Store/ManageSubscription/ManageSubscription-context';
import { ManageSubscriptionContext } from '../../Store/ManageSubscription/ManageSubscription-context';
import type { PlanModel } from '../../Store/User/user-context.helper';
import type { CompanyDbModel } from '../Companies/Components/CompaniesComponents.helper';
import cardStyles from '../Financials/Components/FinancialsCards/FinancialsCards.module.scss';
import { selectedDemoFinancials } from '../Financials/Components/UI/demo-user.helper';
import styles from '../SignUp/SignUp.module.scss';
import type { Action, ManageSubscriptionInterface } from './Components/ManageSubscriptionHelper';
import ManageSubscriptionReducerHelper, {
	ManageSubscriptionPlan,
	manageSubscriptionState
} from './Components/ManageSubscriptionHelper';
import ManageSubscriptionWording from './Components/ManageSubscriptionWording';
import SubscriptionCard from './SubscriptionCard';
import addedStyle from './SubscriptionCard.module.scss';
// eslint-disable-next-line import/no-cycle
import { fetchPaymentData } from '../../ReduxState/payment/paymentHistorySlice';
import { hasAdminPermission } from '../../utils/getUserPermissions';
import { ChevronLeft } from 'lucide-react';

const { apiUrl, backendRoutes } = environment;

export interface PaymentInterface {
	payment_details: {
		id: string;
		create_time: string;
		update_time: string;
		payer: {
			payer_id: string;
			email_address: string;
			name: {
				given_name: string;
				surname: string;
			};
		};
		purchase_units: {
			amount: {
				currency_code: string;
				value: string;
			};
			description: string;
		}[];
	};
	payment_expires: string;
	payment_record_created: string;
	company_id: string;
	cognito_username: string;
}

const ManageSubscription: React.FC = (): JSX.Element => {
	// const { toastNotification } = useUiContext();
	// const checkPermission = (e?: React.MouseEvent<HTMLAnchorElement>): boolean => {
	// 	if (!hasAdminPermission(selectedCompany)) {
	// 		if (e) e.preventDefault();
	// 		toastNotification('info', 'You do not have permission to modify company settings');
	// 		return false;
	// 	}
	// 	return true;
	// };
	let submitting = false;
	const navigate = useNavigate();
	// paypal
	const [showPayment, setShowPayment] = useState(false);
	const createOrder = (data: any = [], actions: any = {}) =>
		actions.order
			.create(currentOrderConfig)
			// eslint-disable-next-line @typescript-eslint/no-shadow
			.then(
				(orderID: any) =>
					// setOrderID(orderID);
					orderID
			);

	/** NEW */
	// const user: UserModel = useSelector((state: RootState) => state.login.user);
	const dispatch = useDispatch<AppDispatch>();
	const availablePlans: PlanModel[] | null = useSelector(
		(state: RootState) => state.applicationGlobal.availablePlans
	);
	const companies: CompanyDbModel[] | null = useSelector(
		(state: RootState) => state.companies.companiesList
	);
	const selectedCompany: CompanyDbModel | null = useSelector(
		(state: RootState) => state.companies.selectedCompany
	);
	const isPaymentExpired: boolean | null = useSelector(
		(state: RootState) => state.payment.paymentExpired
	);
	const [newSelectedPlan, setNewSelectedPlan] = useState<PlanModel | null>(
		selectedCompany?.plan || null
	);

	const getPlanCostById = (planId: number) => {
		if (availablePlans) {
			const plan = availablePlans.find((p) => p.id === planId);
			if (plan?.discountedCost) {
				return plan.discountedCost;
			}
			return plan ? plan.cost : 0;
		}
		return 0;
	};

	// old:
	// const changePlanHandler = (event: FormEvent): void => {
	// 	console.log(
	// 		'plan selected',
	// 		// event.currentTarget.children.item(3),
	// 		event.currentTarget.children.item(3)?.id,
	// 		availablePlans
	// 	);
	// 	// TODO: when switched to display cards below from the availablePlans, remove the +1
	// 	setNewSelectedPlan(
	// 		event.currentTarget.children.item(3)?.id && availablePlans
	// 			? availablePlans[+(event.currentTarget.children.item(3)?.id as unknown as number) + 1]
	// 			: null
	// 	);
	// };

	const changePlanHandler = (id: number): void => {
		console.log(
			'plan selected',
			// event.currentTarget.children.item(3),
			id,
			availablePlans
		);
		// TODO: when switched to display cards below from the availablePlans, remove the +1
		setNewSelectedPlan(id && availablePlans ? availablePlans[id] : null);
	};

	// get payment history from database
	const getPayment = async () => {
		if (selectedCompany) {
			await axios
				.get(`${apiUrl}/account/payment-history?companyId=${selectedCompany.company_id}`)
				.then((response) => {
					setPaymentHistory(response.data);
				});
		}
	};

	useEffect(() => {
		if (selectedCompany) getPayment();
	}, [selectedCompany]);

	function goBack() {
		navigate(-1);
	}

	const cancelAddCompany = () => {
		dispatch(selectCompany(null));
		navigate('/joinOrAddCompany');
	};

	const calculateRemainingDays = (filteredPayment: PaymentInterface[]): number => {
		const now = new Date();
		const paymentsExpireDaysArray: string[] = [];

		filteredPayment.forEach((payment: PaymentInterface) => {
			const lastPaymentExpires = new Date(payment.payment_expires);
			const daysLeft = lastPaymentExpires.getTime() - now.getTime();
			const expireDaysLeft = Math.ceil(daysLeft / (1000 * 3600 * 24)).toString();
			paymentsExpireDaysArray.push(expireDaysLeft);
		});

		const remainingDays = paymentsExpireDaysArray.reduce(
			(previousValue, currentValue) => +previousValue + +currentValue,
			0
		);
		return remainingDays;
	};

	const getPrepaidPlanByTitle = (planTitle: string): PlanModel | undefined =>
		deferredAvailablePlans?.filter((plan) => plan.title === planTitle)[0];

	// const shouldAskForPayment = (el: ShouldAskForPaymentPropsInterface): boolean => {
	const shouldAskForPayment = (): boolean => {
		const now = new Date();
		// do not ask for payment if selected plan is Basic
		if (newSelectedPlan && (newSelectedPlan?.id === 0 || newSelectedPlan?.id === 1)) {
			// setAskForPayment(false);
			return false;
		}

		// it may be needed when payment through settings is enabled
		// if (makeNewPayment) {
		// 	setAskForPayment(true);
		// 	return true;
		// }

		let remainingDaysFromAllPayments = 0;
		if (Array.isArray(paymentHistory) && paymentHistory.length > 0) {
			const filteredProPlanPayments = paymentHistory.filter(
				(item) => item.payment_details.purchase_units[0].description === 'Pro Plan'
			);
			const filteredGrowPlanPayments = paymentHistory.filter(
				(item) => item.payment_details.purchase_units[0].description === 'Grow Plan'
			);

			if (filteredProPlanPayments.length === 0 && filteredGrowPlanPayments.length > 0) {
				remainingDaysFromAllPayments = calculateRemainingDays(filteredGrowPlanPayments);
			} else if (filteredProPlanPayments.length > 0) {
				remainingDaysFromAllPayments = calculateRemainingDays(filteredProPlanPayments);
			}

			const lastPayment: PaymentInterface = paymentHistory.at(-1) as PaymentInterface;
			const prepaidPlan: PlanModel | undefined = getPrepaidPlanByTitle(
				lastPayment.payment_details.purchase_units[0].description
			);

			if (
				(prepaidPlan?.id === 1 && newSelectedPlan?.id === 2) ||
				(prepaidPlan?.id === 2 && newSelectedPlan?.id === 3)
			) {
				// setAskForPayment(true);
				return true;
			}

			if (prepaidPlan) {
				const lastPaymentExpires = new Date(lastPayment.payment_expires);
				if (now > lastPaymentExpires) {
					// Payment has expired, return true if current plan id > 0
					// return !(currentPlan?.id === 1);
					// setAskForPayment(newSelectedPlan?.id === 1);
					return newSelectedPlan?.id === 1;
				}

				// payment has not expired
				if (newSelectedPlan && (newSelectedPlan as PlanModel).id === 1) {
					// don't ask for payment if plan is Basic or
					// the new plan is lower or equal to the paid one
					// setAskForPayment(false);
					return false;
				}

				// ask for payment in any other case
				// setAskForPayment(true);
				return true;
			}
		}
		// setAskForPayment(true);
		return true;
	};

	const submitHandler = (event: FormEvent): void => {
		event.preventDefault();
		// if showPayment already set
		// or user selected BasicPLan
		// or user still has remaining time
		// submit the selected time, otherwise set the show payment modal
		if (showPayment || !shouldAskForPayment()) {
			submitSubscriptionPlan();
		} else {
			setShowPayment(true);
		}
	};
	/** END NEW */

	const accountContext: AccountContextModel = useContext(AccountContext);
	// const companyContext: CompanyContextModel = useContext<CompanyContextModel>(CompaniesContext);
	const globalState: GlobalStateModel = useContext(GlobalStateContext);
	// const currentIdPlan = loggedInUser ? loggedInUser.plan.id - 1 : 0;
	const [idPlan, setIdPlan] = useState<number>(
		globalState.loggedInUser ? globalState.loggedInUser.plan.id - 1 : 0
	);

	const [currentOrderConfig, setOrderConfig] = useState<any>();
	// const { billingDetails, moneyForCeos, dashboard, successPaidPage } = environment.frontendRoutes;
	const { dashboard, successPaidPage } = environment.frontendRoutes;

	// const [linkToNextPage, setLinkToNextPage] = useState<string>(moneyForCeos);
	const [needToPayDifference, setNeedToPayDifference] = useState<number>(0);
	const [completedTransaction, setCompletedTransaction] = useState<boolean>(false);
	const [paymentHistory, setPaymentHistory] = useState<PaymentInterface[] | string>([]);

	function subscriptionHandler(
		state: ManageSubscriptionInterface,
		action: Action
	): ManageSubscriptionInterface {
		return ManageSubscriptionReducerHelper(state, action, manageSubscriptionState);
	}

	const [manageSubscription, dispatchManageSubscription] = useReducer(
		subscriptionHandler,
		manageSubscriptionState
	);
	const manageSubscriptionContext: ManageSubscriptionContextModel =
		useContext(ManageSubscriptionContext);
	const deferredAvailablePlans: PlanModel[] | null = useDeferredValue(
		globalState.getAvailablePlans()
	);

	useEffect(() => {
		function orderHandler(): void {
			// TODO: uncomment and adjust exireDaysLeft calculation if we decide
			// to charge only for the days used in the account
			// if (paymentHistory && Array.isArray(paymentHistory)) {
			// 	const now = new Date();
			// 	const expiresOn = (paymentHistory[0] as PaymentInterface)?.payment_expires;
			// 	const lastPaymentExpires = new Date(expiresOn);
			// 	const daysLeft = lastPaymentExpires.getTime() - now.getTime();
			// 	let expireDaysLeft;

			// 	if (now.getTime() < lastPaymentExpires.getTime()) {
			// 		expireDaysLeft = Math.ceil(daysLeft / (1000 * 3600 * 24)).toString();
			// 	}
			// 	const paid = (newSelectedPlan?.cost as number);
			// 	const daysInThisYear = new Date().getFullYear() % 4 === 0 ? 366 : 365;
			// 	const usedPaidDays = daysInThisYear - +(expireDaysLeft as string);
			// 	setNeedToPayDifference((+paid / daysInThisYear) * usedPaidDays);
			// }

			if (selectedCompany?.plan?.id === 2 && newSelectedPlan?.id === 3) {
				if (!newSelectedPlan?.id) return;
				const newSelectedPlanCost = getPlanCostById(newSelectedPlan.id) * 12 * 1.2; // 1.2 is the tax
				const currentPlanCost = getPlanCostById(selectedCompany.plan.id) * 12 * 1.2; // 1.2 is the tax
				if (newSelectedPlanCost === 0 || currentPlanCost === 0) return;
				let ammountDue = newSelectedPlanCost - currentPlanCost;
				if (newSelectedPlan.discountedCost || selectedCompany.plan.discountedCost) {
					const currentPlanCost = selectedCompany.plan.discountedCost || selectedCompany.plan.cost;
					const newPlanCost = newSelectedPlan.discountedCost || newSelectedPlan.cost;
					ammountDue =
						newPlanCost > currentPlanCost
							? (newPlanCost - currentPlanCost) * 12 * 1.2
							: (newSelectedPlan.cost - currentPlanCost) * 12 * 1.2;
				}
				setOrderConfig({
					purchase_units: [
						{
							description: newSelectedPlan?.title,
							amount: {
								currency_code: 'USD', // TODO: change to GBP for live
								value: ammountDue.toFixed(2)
							}
						}
					],
					application_context: {
						shipping_preference: 'NO_SHIPPING'
					}
				});
			}
		}

		// set the currentOrderConfig
		console.log('plan cost', newSelectedPlan?.cost, newSelectedPlan?.cost as number);
		if (!newSelectedPlan?.id) return;
		const newSelectedPlanCost = getPlanCostById(newSelectedPlan.id) * 12 * 1.2;
		setOrderConfig({
			purchase_units: [
				{
					description: newSelectedPlan?.title,
					amount: {
						currency_code: 'USD', // TODO: change to EUR for live
						value: newSelectedPlanCost.toFixed(2)
					}
				}
			],
			application_context: {
				shipping_preference: 'NO_SHIPPING'
			}
		});

		if (selectedCompany?.plan?.id && selectedCompany?.plan?.id > 1) {
			orderHandler();
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [newSelectedPlan, selectedCompany]);

	const downgradePlan = async () => {
		if (selectedCompany && newSelectedPlan && newSelectedPlan?.id < selectedCompany?.plan?.id) {
			dispatch(downgradeCompanyPlan({ company_id: selectedCompany.company_id, newSelectedPlan }))
				.then(() => {
					goBack();
				})
				.catch((error) => {
					// TODO: throw an error/display error modal
					console.error(error);
					// eslint-disable-next-line no-alert
					alert('Something went wrong!, we could not update the plan');
				});
		} else {
			// TODO: throw an error/display error modal
			console.log(selectedCompany, newSelectedPlan);
			console.error('error updating plan');
			// eslint-disable-next-line no-alert
			alert('Something went wrong!, we could not update the plan');
		}
	};

	// use it to only update the plan
	// typically when selecting free or when downgrading
	const submitSubscriptionPlan = async () => {
		submitting = true;
		localStorage.removeItem('activateInactiveCompany');
		if (!newSelectedPlan) {
			// eslint-disable-next-line no-alert
			alert('Please choose your plan!');
			submitting = false;
			return;
		}

		if (selectedCompany && newSelectedPlan) {
			dispatch(setCompanyPlan({ company_id: selectedCompany.company_id, newSelectedPlan }))
				.then(() => {
					localStorage.setItem('isClosedPopup', JSON.stringify(false));
					localStorage.removeItem('selected-company');
					localStorage.removeItem('selected-financials');
					// TODO: legacy - to be removed in the future:
					localStorage.removeItem('financials');
					localStorage.removeItem('first-financial');
					localStorage.removeItem('second-financial');
					localStorage.removeItem('third-financial');
					localStorage.removeItem('createdCompanyId');
					setCompletedTransaction(false);
					console.log('new selected plan ', newSelectedPlan);
					if (newSelectedPlan?.id > ManageSubscriptionPlan.basicPlan) {
						// set financials
						localStorage.setItem('isDemoActive', JSON.stringify(false));
						// refresh session payment data
						dispatch(fetchPaymentData({ selectedCompany }));
						// refresh financial data data
						dispatch(fetchFinancialsData({ selectedCompany }));
						// navigate to success paid page
						navigate(successPaidPage);
					} else {
						console.log(
							'setting demo financials and navigating to dashboard ',
							selectedDemoFinancials
						);
						// set DEMO financials
						// localStorage.setItem('isDemoActive', JSON.stringify(true));
						dispatch(setDemoFinancials(selectedDemoFinancials));
						// navigate to dashboard
						navigate(dashboard);
					}
				})
				.catch((error) => {
					// TODO: throw an error/display error modal
					console.error(error);
				});
		} else {
			// TODO: throw an error/display error modal
			console.error('error updating plan');
			// eslint-disable-next-line no-alert
			alert('Something went wrong!, we could not update the plan');
		}
	};

	// writePaymentDetails
	const submitPaymentDetails = async (paymentDetails: any) => {
		submitting = true;
		const submitSuccess = false;
		if (selectedCompany && newSelectedPlan && paymentDetails) {
			setCompletedTransaction(true);
			dispatch(
				payAndSetCompanyPlan({
					paymentDetails,
					company_id: selectedCompany.company_id,
					newSelectedPlan
				})
			)
				.then(() => {
					setTimeout(() => {
						submitting = false;
						localStorage.setItem('isClosedPopup', JSON.stringify(false));
						localStorage.removeItem('selected-company');
						localStorage.removeItem('selected-financials');
						// TODO: legacy - to be removed in the future:
						localStorage.removeItem('financials');
						localStorage.removeItem('first-financial');
						localStorage.removeItem('second-financial');
						localStorage.removeItem('third-financial');
						localStorage.removeItem('createdCompanyId');
						setCompletedTransaction(false);
						// refresh session payment data
						dispatch(fetchPaymentData({ selectedCompany }));
						navigate(successPaidPage);
					}, 3000);
				})
				.catch((error) => {
					submitting = false;
					// TODO: throw an error/display error modal
					console.error(error);
				});
		}
	};

	// on Payment Approval
	const onApprove = (data: any = [], actions: any = {}) =>
		actions.order.capture().then((details: any) => {
			const { payer } = details;
			console.log('details', details);
			console.log('payer', payer);
			submitPaymentDetails(details);
		});

	const isActivate = localStorage.getItem('activateInactiveCompany') === 'true';

	return (
		<PayPalScriptProvider
			options={{
				'client-id':
					'AR04e9SGaUAA7ZDd5fhZuQFSMEZ_99B6ON31wzXnHYsp7te40Obwm6gounDU7iO4c20g1OW7DYpPFncJ',
				locale: 'en_GB'
			}}
		>
			<div className="container">
				<div className={styles.signUpContainer}>
					<SignInHeader />
					{selectedCompany?.plan ? (
						<>
							{!showPayment && !isPaymentExpired && (
								<h4 style={{ textTransform: 'none' }} className="text-gray">
									<div className="fw-bolder text-center mb-1">{selectedCompany?.company_name}</div>
									Your current subscription plan is:{' '}
									<span className={styles.subscriptionPlan}>{selectedCompany?.plan?.title}</span>
								</h4>
							)}
							{!showPayment && isPaymentExpired && (
								<h4 style={{ textTransform: 'none' }}>
									<div className="fw-bolder text-center mb-1">{selectedCompany?.company_name}</div>
									Renew subscription for plan:{' '}
									<span className={styles.subscriptionPlan}>{selectedCompany?.plan?.title}</span>
								</h4>
							)}
							{showPayment && newSelectedPlan && (
								<h4 className="text-gray">
									You have selected the:{' '}
									<span className={styles.subscriptionPlan}>{newSelectedPlan?.title}</span>
								</h4>
							)}
							{!showPayment && <div>Choose a new subscription plan</div>}
							{showPayment && newSelectedPlan && (
								<>
									<div>Proceed to payment in order to activate your new plan.</div>
									<div>
										You will now be directed to our third party payment processor PayPal to process
										your payment.
									</div>
								</>
							)}
						</>
					) : (
						<>
							{!showPayment && (
								<h4 style={{ textTransform: 'none' }} className="text-gray">
									{isActivate && (
										<div className="fw-bolder text-center mb-1">
											{selectedCompany?.company_name}
										</div>
									)}
									Please, choose your subscription plan
								</h4>
							)}
							{showPayment && newSelectedPlan && (
								<h4 style={{ textTransform: 'none', display: 'flex' }} className="text-gray">
									You have selected the:{' '}
									<span className={styles.subscriptionPlan}>{newSelectedPlan?.title}</span>
								</h4>
							)}
						</>
					)}
				</div>
				<div className={[cardStyles.cardsContainer, addedStyle.cardsContainer].join(' ')}>
					{showPayment ? (
						<div className={styles.paypalWwrapper}>
							<PayPalButtons
								createOrder={createOrder}
								onApprove={onApprove}
								style={{
									layout: 'vertical'
								}}
							/>
							<div className="mt-3">
								<Link to="#" onClick={() => setShowPayment(false)} className={styles.backButton}>
									<ChevronLeft size={16} /> Select another plan
								</Link>
							</div>
						</div>
					) : (
						<form className={cardStyles.form} onSubmit={submitHandler}>
							<div className={[cardStyles.card, addedStyle.card].join(' ')}>
								<SubscriptionCard
									cardContainer={[cardStyles.cardContainer, addedStyle.cardContainer].join(' ')}
									fee="FREE"
									feeType=""
									label="Basic plan"
									// onChange={changePlanHandler(1)}
									onClick={() => changePlanHandler(1)}
									radioButtonClass={
										newSelectedPlan && newSelectedPlan?.id === 1
											? cardStyles.active
											: cardStyles.nonActive
									}
									radioId="0"
									radioName="plan"
									radioValue="basicPlan"
									wordingList={ManageSubscriptionWording.basic}
									// checklist={['1', '2', '3']}
								/>
								<SubscriptionCard
									cardContainer={[cardStyles.cardContainer, addedStyle.cardContainer].join(' ')}
									fee={availablePlans ? `£${availablePlans[2].cost.toString()}` : '£66.67'}
									discountedFee={
										availablePlans && availablePlans[2].discountedCost
											? `£${availablePlans[2]?.discountedCost.toString()}`
											: null
									}
									feeType=" / month billed annually"
									label="Grow plan"
									// onChange={changePlanHandler(2)}
									onClick={() => changePlanHandler(2)}
									radioButtonClass={
										newSelectedPlan && newSelectedPlan?.id === 2
											? cardStyles.active
											: cardStyles.nonActive
									}
									radioId="1"
									radioName="plan"
									radioValue="growPlan"
									wordingList={ManageSubscriptionWording.grow}
									// checklist={['1', '2', '3']}
								/>
								<SubscriptionCard
									cardContainer={[cardStyles.cardContainer, addedStyle.cardContainer].join(' ')}
									fee={availablePlans ? `£${availablePlans[3].cost.toString()}` : '£83.33'}
									discountedFee={
										availablePlans && availablePlans[3].discountedCost
											? `£${availablePlans[3]?.discountedCost.toString()}`
											: null
									}
									feeType=" / month billed annually"
									label="Pro plan"
									// onChange={changePlanHandler(3)}
									onClick={() => changePlanHandler(3)}
									radioButtonClass={
										newSelectedPlan && newSelectedPlan?.id === 3
											? cardStyles.active
											: cardStyles.nonActive
									}
									radioId="2"
									radioName="plan"
									radioValue="proPlan"
									wordingList={ManageSubscriptionWording.pro}
									// checklist={['1', '2', '3']}
								/>
							</div>
							{/* TODO: remove manageSubscription references */}
							{/* companyType = 'Advisor' is deprecated */}
							{/* {accountContext.companyType === 'Advisor' && (
								<>
									<h5>Reporting for number of clients</h5>
									<div
										className={[cardStyles.card, addedStyle.card, addedStyle.numberCard].join(' ')}
									>
										<SubscriptionCard
											cardContainer={[
												cardStyles.cardContainer,
												addedStyle.cardContainer,
												manageSubscription.clients1,
												cardStyles.clientsCards
											].join(' ')}
											fee="Included"
											feeType=""
											label="3"
											// onChange={changePlanHandler}
											onClick={changePlanHandler}
											radioButtonClass={manageSubscription.clients1}
											radioId="3"
											radioName="clients"
											radioValue="3"
											wordingList={[]}
											// checklist={['1', '2', '3']}
										/>
										<SubscriptionCard
											cardContainer={[
												cardStyles.cardContainer,
												addedStyle.cardContainer,
												manageSubscription.clients2,
												cardStyles.clientsCards
											].join(' ')}
											fee="+ £6/month"
											feeType=""
											label="10"
											// onChange={changePlanHandler}
											onClick={changePlanHandler}
											radioButtonClass={manageSubscription.clients2}
											radioId="10"
											radioName="clients"
											radioValue="10"
											wordingList={[]}
											// checklist={['1', '2', '3']}
										/>
										<SubscriptionCard
											cardContainer={[
												cardStyles.cardContainer,
												addedStyle.cardContainer,
												manageSubscription.clients3,
												cardStyles.clientsCards
											].join(' ')}
											fee="+ £13/month"
											feeType=""
											label="25"
											// onChange={changePlanHandler}
											onClick={changePlanHandler}
											radioButtonClass={manageSubscription.clients3}
											radioId="25"
											radioName="clients"
											radioValue="25"
											wordingList={[]}
											// checklist={['1', '2', '3']}
										/>
										<SubscriptionCard
											cardContainer={[
												cardStyles.cardContainer,
												addedStyle.cardContainer,
												manageSubscription.clients4,
												cardStyles.clientsCards
											].join(' ')}
											fee="+ £26/month"
											feeType=""
											label="50"
											// onChange={changePlanHandler}
											onClick={changePlanHandler}
											radioButtonClass={manageSubscription.clients4}
											radioId="50"
											radioName="clients"
											radioValue="50"
											wordingList={[]}
											// checklist={['1', '2', '3']}
										/>
									</div>
								</>
							)} */}

							{newSelectedPlan &&
								selectedCompany?.plan?.id &&
								newSelectedPlan?.id < selectedCompany?.plan?.id && (
									<p className={cardStyles.warning}>
										You are about to downgrade your plan. This will take effect from your next
										billing cycle.
									</p>
								)}

							<div className="d-flex flex-row">
								{newSelectedPlan &&
								selectedCompany?.plan?.id &&
								newSelectedPlan?.id < selectedCompany?.plan?.id ? (
									<Button
										className={classNames(cardStyles.submitButton, addedStyle.submitButton, {
											[cardStyles.submitting]: submitting
										})}
										// type="submit"
										variant="contained"
										onClick={() => {
											downgradePlan();
										}}
									>
										<span>Downgrade plan</span>
									</Button>
								) : (
									<>
										{!selectedCompany?.plan?.id && (
											<button
												className={classNames(globalStyle.cancelButton, 'mr-4', {
													[cardStyles.submitting]: submitting
												})}
												// type="submit"
												onClick={() => {
													cancelAddCompany();
												}}
											>
												<span>Cancel</span>
											</button>
										)}
										{/* <Button
											className={classNames(cardStyles.submitButton, addedStyle.submitButton, {
												[cardStyles.submitting]: submitting
											})}
											type="submit"
											variant="contained"
											disabled={
												!hasAdminPermission(selectedCompany) ||
												!newSelectedPlan ||
												(newSelectedPlan?.id === selectedCompany?.plan?.id && !isPaymentExpired)
											}
										>
											<span>Activate plan</span>
										</Button> */}
										<button
											className={classNames(globalStyle.submitButton, {
												[cardStyles.submitting]: submitting
											})}
											type="submit"
											disabled={
												!hasAdminPermission(selectedCompany) ||
												!newSelectedPlan ||
												(newSelectedPlan?.id === selectedCompany?.plan?.id && !isPaymentExpired)
											}
										>
											<span>Activate plan</span>
										</button>
									</>
								)}
								{selectedCompany &&
									selectedCompany?.plan &&
									selectedCompany?.plan?.title !== 'Unassigned' && (
										<Button
											style={{ marginLeft: '20px' }}
											className={classNames(globalStyle.cancelButton, {
												[cardStyles.submitting]: submitting
											})}
											onClick={goBack}
										>
											<span>Keep my current plan</span>
										</Button>
									)}
							</div>
						</form>
					)}
					{completedTransaction && (
						<div className={styles.transactionCompleteMessage}>
							<h3>Thank you for purchasing the {newSelectedPlan?.title}</h3>
							<p className={styles.transactionCompleteMessage__paragraph}>
								The transaction is completed
							</p>
						</div>
					)}
				</div>
			</div>
		</PayPalScriptProvider>
	);
};
export default ManageSubscription;
