/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react/no-array-index-key */
/* eslint-disable react/button-has-type */
import axios from 'axios';
import classNames from 'classnames';
import { useDeferredValue, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

import globalStyle from '../../Components/GlobalStyles/globals.module.scss';
import { CompanySettingsSvg } from '../../Components/Layout/Header/Components/UI/HeaderButtonsSvg';
import InsightsHeader from '../../Components/Layout/Header/InsightsHeader';
import environment from '../../Environments/environment';
import type { RootState } from '../../ReduxState/store';
import type { UserModel } from '../../Store/User/user-context.helper';
import AccountNavBar from '../Account/Components/AccountNavBar';
import type { CompanyDbModel } from '../Companies/Components/CompaniesComponents.helper';
import type { PaymentInterface } from '../ManageSubscription/ManageSubscription';
import globalStyles from '../../Components/GlobalStyles/globalSettings.module.scss';
import styles from './PaymentHistory.module.scss';
import isPaymentExpired from './Helpers/PaymentExpired';
import { useUiContext } from '../../Store/UiContext/UiContext';
import { hasAdminPermission } from '../../utils/getUserPermissions';

const PaymentHistory = (): JSX.Element => {
	const [payments, setPayments] = useState<PaymentInterface[] | null>(null);
	const { apiUrl, frontendRoutes } = environment;
	const navigate = useNavigate();
	const { toastNotification } = useUiContext();
	const selectedUser = useSelector((state: RootState): UserModel | null => state.login.user);
	const selectedCompany = useSelector(
		(state: RootState): CompanyDbModel | null => state.companies.selectedCompany
	);
	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;
	};

	const getCurrencySymbol = (currencyCode: string) => {
		const locale = 'en-US';
		const currencyValue = 0; // Dummy value
		const formatter = new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: currencyCode
		});
		const parts = formatter.formatToParts(currencyValue);

		let currencySymbol = '';
		for (const part of parts) {
			if (part.type === 'currency') {
				currencySymbol += part.value;
			}
		}

		return currencySymbol;
	};

	const getPaymentHistoryHandler = async () => {
		if (!selectedCompany) return;
		await axios(`${apiUrl}/account/payment-history?companyId=${selectedCompany?.company_id}`).then(
			(response) => {
				if (response.status === 200) {
					setPayments(response.data);
				}
			}
		);
	};

	useEffect(() => {
		getPaymentHistoryHandler();
	}, [selectedCompany]);
	/** NEW end */
	const sufficientPermissions = () => {
		if (
			selectedCompany?.permissions === 'admin' ||
			selectedCompany?.role?.toLocaleLowerCase() === 'owner' || // backward compatibility
			selectedCompany?.role?.toLocaleLowerCase() === 'ceo' || // backward compatibility
			selectedCompany?.owner?.cognito_username === selectedUser?.cognito_username
		)
			return true;
		return false;
	};

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

	const formatDate = (dateString: string) => {
		const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric' };
		return new Date(dateString).toLocaleDateString('en-GB', options);
	};

	// const isPaymentExpired = (paymentExpires: string | null, stylesClass: string) => {
	// 	if (paymentExpires === null) {
	// 		return [null, null];
	// 	}

	// 	const lastPaymentExpires = new Date(paymentExpires);
	// 	const daysLeft = lastPaymentExpires.getTime() - now.getTime();
	// 	let expireDaysLeft;
	// 	let expireDaysLeftClass = '';
	// 	if (now.getTime() < lastPaymentExpires.getTime()) {
	// 		expireDaysLeft = Math.ceil(daysLeft / (1000 * 3600 * 24)).toString();
	// 	} else {
	// 		expireDaysLeft = Math.ceil(
	// 			(now.getTime() - lastPaymentExpires.getTime()) / (1000 * 3600 * 24)
	// 		).toString();
	// 		expireDaysLeft = `expired ${expireDaysLeft} ago`;
	// 		expireDaysLeftClass = styles.red;
	// 	}

	// 	console.log('returning', expireDaysLeft, expireDaysLeftClass);
	// 	return [expireDaysLeft, expireDaysLeftClass];
	// };

	const generateInvoice = async (invoiceInfo: PaymentInterface) => {
		const { payment_details } = invoiceInfo;
		const { payer } = payment_details;
		const invoiceDate = new Date(payment_details.create_time);
		const dueDate = new Date(payment_details.create_time);
		const dueDays = 30;
		dueDate.setDate(dueDate.getDate() + dueDays);
		const jsonData = {
			invoiceNumber: payment_details.id,
			name: `${payer.name.given_name} ${payer.name.surname}`,
			companyName: selectedCompany?.company_name,
			companyAddress: selectedCompany?.company_address,
			zipCode: '/',
			city: '/',
			country: 'UK',
			issueDate: invoiceDate.toLocaleDateString('en-GB'),
			dueDate: dueDate.toLocaleDateString('en-GB'),
			planName: selectedCompany?.plan.title,
			currencySign: payment_details.purchase_units[0].amount.currency_code,
			amount: payment_details.purchase_units[0].amount.value,
			fullAmount: (+payment_details.purchase_units[0].amount.value * 1.2).toFixed(2)
		};
		const apiUrl = environment.pdfUrl;
		try {
			const response = await axios.post(
				apiUrl,
				{
					jsonData: JSON.stringify(jsonData),
					htmlTemplateFile: 'invoice'
				},
				{
					responseType: 'blob' // Set the response type to blob to handle binary data
				}
			);

			// Create a new Blob object from the PDF stream
			const pdfBlob = new Blob([response.data], { type: 'application/pdf' });

			// Create a link element
			const link = document.createElement('a');
			link.href = URL.createObjectURL(pdfBlob); // Create an object URL for the blob
			link.download = `invoice-${payment_details.id}.pdf`; // Set the file name for the downloaded file

			// Append the link to the body (even though it's not visually rendered)
			document.body.appendChild(link);

			// Programmatically click the link to trigger the download
			link.click();

			// Clean up and remove the link element from the DOM
			document.body.removeChild(link);
		} catch (error) {
			console.error('Error downloading PDF:', error);
		}
	};

	const renderInvoiceList = (deferredPaymentValue: PaymentInterface[] | string | null) => {
		if (deferredPaymentValue && Array.isArray(deferredPaymentValue)) {
			const ret: any[] = [];

			deferredPaymentValue.forEach((bill, index) => {
				const { payer } = bill.payment_details;
				const renderExpireDaysLeft = false;
				if (renderExpireDaysLeft) {
					// not in use any more, but if needed in future can be put to use
					const [expireDaysLeft, expireDaysLeftClass] = isPaymentExpired(
						bill.payment_expires,
						styles.red
					);
				}

				ret.push(
					<li key={index} className={styles.container__main__list__element}>
						{/* <p>{payer.name.given_name}</p>
																	<p>{payer.name.surname}</p>
																	<p>
																		{getCurrencySymbol(
																			bill.payment_details.purchase_units[0].amount.currency_code
																		)}
																		{bill.payment_details.purchase_units[0].amount.value}
																	</p>
																	<p>{bill.payment_details.purchase_units[0].description}</p>
																	<p className={expireDaysLeftClass}>{expireDaysLeft}</p> */}

						<p>{formatDate(bill.payment_record_created)}</p>
						<p>{bill.payment_details.purchase_units[0].description}</p>
						<p>Annual</p>
						<p>
							{getCurrencySymbol(bill.payment_details.purchase_units[0].amount.currency_code)}
							{bill.payment_details.purchase_units[0].amount.value}
						</p>
						<p>Paid</p>
						<p>
							<a
								href="#"
								className={styles.viewInvoice}
								onClick={(e) => {
									e.preventDefault();
									generateInvoice(bill);
								}}
							>
								View Invoice
							</a>
						</p>
					</li>
				);
			});

			return ret;
		}

		return null;
	};

	const deferredPaymentValue = useDeferredValue(payments);
	console.log('PAYMENT VALUES', deferredPaymentValue);
	const now = new Date();
	return (
		<div className={styles.paymentHistoryContainer}>
			<main className={styles.contextContainer}>
				<InsightsHeader numberOfButtons={1} title="Billing" />
				<div className={styles.mainContext}>
					<AccountNavBar />
					{sufficientPermissions() && (
						<div className={globalStyle.settingsContentWrapper}>
							<div className={styles.container__main}>
								{/* <h5>
									<CompanySettingsSvg /> Billing History
								</h5> */}
								<h3 className={globalStyles.h3Wrapper}>
									<CompanySettingsSvg />
									Billing History
								</h3>
								{deferredPaymentValue && deferredPaymentValue.length > 0 && (
									<>
										<div className={`${styles.nextBilingCycle} mt-4`}>
											<div
												className={classNames(
													styles.nextBilingCycle__row,
													styles.nextBilingCycle__title
												)}
											>
												<div>Next invoice issue date</div>
												<div>Days left</div>
												<div>Invoice total</div>
											</div>
											<div
												className={classNames(
													styles.nextBilingCycle__row,
													styles.nextBilingCycle__content
												)}
											>
												<div>
													{formatDate(
														deferredPaymentValue && deferredPaymentValue[0]
															? deferredPaymentValue[0].payment_expires
															: new Date().toISOString()
													)}
												</div>
												<div>
													{
														isPaymentExpired(
															deferredPaymentValue && deferredPaymentValue[0]
																? deferredPaymentValue[0].payment_expires
																: null,
															styles.red
														)[0]
													}
												</div>
												<div>
													{deferredPaymentValue && deferredPaymentValue[0]
														? `${getCurrencySymbol(
																deferredPaymentValue[0].payment_details.purchase_units[0].amount
																	.currency_code
														  )}${
																deferredPaymentValue[0].payment_details.purchase_units[0].amount
																	.value
														  }`
														: selectedCompany?.plan.cost}
												</div>
											</div>
										</div>

										<>
											<h6>Invoices</h6>
											<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> */}

												<li className={styles.container__main__list__element__title}>
													<p>Date</p>
													<p>Description</p>
													<p>Cycle</p>
													<p>Invoice total</p>
													{/* <p>Status</p> */}
													<p>Status</p>
													<p />
												</li>

												{renderInvoiceList(deferredPaymentValue)}
											</ul>
										</>
									</>
								)}
								{deferredPaymentValue && deferredPaymentValue.length === 0 && (
									<p>No payment has been made for this company so far!</p>
								)}
								<div className={styles.buttonWrapper}>
									<button className={globalStyle.submitButton} onClick={updatePaymentHandler}>
										<span>
											{deferredPaymentValue && deferredPaymentValue.length === 0
												? 'Make a payment'
												: 'Upgrade/Renew plan'}
										</span>
									</button>
								</div>
							</div>
						</div>
					)}
					{!sufficientPermissions() && (
						<div className={globalStyle.settingsContentWrapper}>
							<div className={styles.container__main}>
								{/* <h5>
									<CompanySettingsSvg /> Billing History
								</h5> */}
								<h3 className={globalStyles.h3Wrapper}>
									<CompanySettingsSvg />
									Billing History
								</h3>
								{/* <ul className={styles.container__main__list}> */}
								<p>You don't have sufficient permissions to view this page</p>
								{/* </ul> */}
							</div>
						</div>
					)}
				</div>
			</main>
		</div>
	);
};
export default PaymentHistory;
