import React, {
 useContext, useDeferredValue, useEffect, useState
} from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import styles from './PaymentHistory.module.scss';
import InsightsHeader from '../../Components/Layout/Header/InsightsHeader';
import { CompanySettingsSvg } from '../../Components/Layout/Header/Components/UI/HeaderButtonsSvg';
import { PlanModel, UserModel } from '../../Store/User/user-context.helper';
import environment from '../../Environments/environment';
import { PaymentInterface } from '../ManageSubscription/ManageSubscription';
import {
		ManageSubscriptionContext,
		ManageSubscriptionContextModel
} from '../../Store/ManageSubscription/ManageSubscription-context';
import { GlobalStateContext, GlobalStateModel } from '../../Store/global/GlobalState-context';
import AccountNavBar from '../Account/Components/AccountNavBar';

export default function PaymentHistory() : JSX.Element {
		const [payments, setPayments] = useState<PaymentInterface[] | string>('no plan is selected');
		const globalState : GlobalStateModel = useContext(GlobalStateContext);
		const [availablePlans, setAvailablePlans] = useState<PlanModel[] | null>(null);
		const {
				apiUrl,
				frontendRoutes
		} = environment;
		const navigate = useNavigate();
		const manageSubscriptionContext : ManageSubscriptionContextModel =
				useContext(ManageSubscriptionContext);
		const deferredUserType : UserModel = useDeferredValue(
				JSON.parse(localStorage.getItem('accountType') as string));

		useEffect(() => {
				// if (deferredUserType?.account_type?.title === 'Advisor') {
				// 		navigate('/dashboard');
				// }
		}, []);

		useState(() => {
				if (globalState.getAvailablePlans()) {
						setAvailablePlans(globalState.getAvailablePlans());
				}

				// TOREVIEW: the call to get payment history here is not needed
				// as we already have a method setup in global context which
				// is handling this situation. If needed to make sure that the state is not changed
				// use the method `getPaymentHistoryHandler` from GlobalContext
				// axios
				// 		.get(`${apiUrl}/account/add-payment-history?
				// companyId=${globalState.selectedCompany.company_id}`)
				// 		.then((response) => {
				// 				if (typeof response.data !== 'string') {
				// 						setPayments(response.data);
				// 				}
				// 		});
		});

		function updatePaymentHandler() {
				navigate(frontendRoutes.manageSubscription);
				localStorage.setItem('makeNewPayment', JSON.stringify(true));
		}

		// const deferredValue = useDeferredValue(payments);
		const deferredValue = globalState.payments;
		const now = new Date();
		return <div className={styles.container}>
				<InsightsHeader numberOfButtons={1} title={'Billing Details'} />
				<div className={styles.navbarBodyWrapper}>
						<div className={styles.subNavBar}>
								<AccountNavBar/>
						</div>
						<div className={styles.container__main}>
								<h5><CompanySettingsSvg /> Billing History</h5>
								<ul className={styles.container__main__list}>
										<li className={styles.container__main__list__element__title}>
												<p>Name</p>
												<p>Surname</p>
												<p>Paid</p>
												<p>Purchased Plan</p>
												<p>Days Left</p>
										</li>
										{(typeof deferredValue !== 'string') &&
												(deferredValue as PaymentInterface[]).map((bill, index) => {
														const {
																payer
														} = bill.payment_details;
														const lastPaymentExpires = new Date(bill.payment_expires);
														const daysLeft = lastPaymentExpires.getTime() - now.getTime();
														let expireDaysLeft;
														//
														if (now.getTime() < lastPaymentExpires.getTime()) {
																expireDaysLeft = (Math.ceil(daysLeft / (1000 * 3600 * 24))
																		.toString());
														}

														return <li
																key={index}
																className={styles.container__main__list__element}>
																<p>{payer.name.given_name}</p>
																<p>{payer.name.surname}</p>
																<p>${bill.payment_details.purchase_units[0].amount.value}</p>
																<p>{bill.payment_details.purchase_units[0].description}</p>
																<p>{expireDaysLeft}</p>
														</li>;
												})}
								</ul>
								<button
										className={styles.container__main__button}
										onClick={updatePaymentHandler}>
										Make a New Payment
								</button>
						</div>
				</div>
		</div>;
}
