import { useEffect, useState } from 'react';
import type { CompanyDbModel } from '../../../Companies/Components/CompaniesComponents.helper';
import { useUiContext } from '../../../../Store/UiContext/UiContext';
import { useDispatch, useSelector } from 'react-redux';
import type { AppDispatch, RootState } from '../../../../ReduxState/store';
import {
	downloadMultipleCSVsAsZip,
	getFinancialsList,
	getInvitesList,
	getPaymentInfo
} from './DeleteCompany.helper';
import type { FinancialsModel } from '../../../Financials/Components/FinancialsForm/FinancialsForm.helper';
import type { InvitedUserInterface } from '../../Pages/ManageUsers/Components/ManageUsersPage';
import { deleteCompany } from '../../../../ReduxState/companies/companiesSlice';
import { Button } from '@mui/material';
import { DeleteOutline } from '@mui/icons-material';
import { hasAdminPermission, hasOwnerPermission } from '../../../../utils/getUserPermissions';
import type { PaymentInterface } from '../../../ManageSubscription/ManageSubscription';
// import { isPaymentExpired } from '../../../../ReduxState/payment/paymentHistorySlice';
import styles from './DeleteCompany.module.scss';
import { useNavigate } from 'react-router-dom';
import type { UserModel } from '../../../../Store/User/user-context.helper';

const DeleteCompany = ({
	// deleteCompany
	companyData,
	displayAs = 'link'
}: {
	// deleteCompany: (companyData: CompanyDbModel) => void;
	companyData: CompanyDbModel | null | undefined;
	displayAs?: 'link' | 'icon';
}): JSX.Element => {
	const { toastNotification, confirmModal } = useUiContext();
	const dispatch = useDispatch<AppDispatch>();
	const navigate = useNavigate();
	const selectedUser = useSelector((state: RootState): UserModel | null => state.login.user);
	// const invites: InvitedUserInterface[] | null = useSelector(
	// 	(state: RootState) => state.invites.invitesList
	// );

	const checkPermission = (e?: React.MouseEvent<HTMLAnchorElement>): boolean => {
		if (!hasAdminPermission(companyData)) {
			if (e) e.preventDefault();
			toastNotification('info', 'You do not have permission to modify company settings');
			return false;
		}
		if (!hasOwnerPermission(companyData, selectedUser)) {
			if (e) e.preventDefault();
			toastNotification('info', 'Only the Account Subscriber can delete this company');
			return false;
		}
		return true;
	};

	const [financialsList, setFinancialsList] = useState<FinancialsModel[] | null>([]);
	const [invitesList, setInvitesList] = useState<InvitedUserInterface[] | null>([]);
	const [acceptedInvitesList, setAcceptedInvitesList] = useState<InvitedUserInterface[] | null>([]);
	const [paymentInfo, setPaymentInfo] = useState<PaymentInterface[] | null>([]);
	useEffect(() => {
		console.log('getting financials list for company: ', companyData?.company_id);
		getFinancialsList(companyData?.company_id).then((financials) => {
			console.log('setting financials list for company: ', companyData?.company_id, financials);
			setFinancialsList(financials);
		});
		getInvitesList(companyData?.company_id).then((invites) => {
			setInvitesList(invites);
			const acceptedInvites = invites.filter(
				(user: InvitedUserInterface) => user.accepted === true && !user.revoked
			);
			setAcceptedInvitesList(acceptedInvites);
		});
		getPaymentInfo(companyData?.company_id).then((paymentInformation) => {
			setPaymentInfo(paymentInformation);
		});
	}, []);

	const errorDeletion = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Company could not be deleted',
			message: 'We could not delete the company. Please try again later or contact support.',
			confirmButtonText: 'Ok'
		});
	};

	const notifyForCheckbox = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Must confirm account deletion',
			message: ['In order to proceed with the delete you must select the confirm checkbox'],
			confirmButtonText: 'Go back'
		});

		if (isConfirmed) {
			// TODO: DELETE THE ACCOUNT
			confimrDeletion();
		} else {
			// do nothing
		}
	};

	const deletionFinalNotification = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'What happens when you delete a company in moneyXplier®?',
			message: [
				'When you delete a company in moneyXplier, we will permanently erase all company-related data, including financial records and forecasts, team member associations and access history and configuration settings and audit logs. This deletion is performed in accordance with GDPR and our data retention policies. Once completed, the company and its data are no longer accessible or recoverable by any users.',
				'We may retain certain anonymised or aggregated usage data to help improve our product and services. This data is fully de-identified and cannot be linked back to any individual or organisation. Where required by law (e.g., for financial or compliance purposes), we will retain only the minimum necessary data for a limited time, as outlined in our Privacy Policy.',

				'Please note that this process is irreversible.'
			],
			confirmButtonText: 'Yes, delete my company',
			confirmButtonColor: 'red',
			cancelButtonText: 'Cancel'
		});

		if (isConfirmed) {
			if (companyData?.company_id) {
				const payload = { company_id: companyData?.company_id };
				dispatch(deleteCompany(payload));
			} else {
				errorDeletion();
			}
		}
	};

	const checkForActiveSubscription = async (): Promise<void> => {
		// skip it until we actually introduce subscription based payments
		// if (paymentInfo && paymentInfo.length > 0) {
		// 	const isExpired = isPaymentExpired(paymentInfo[0]);
		// 	if (!isExpired) {
		// 		const isConfirmed = await confirmModal({
		// 			title: 'Active subscription detected!',
		// 			message:
		// 				// 'You have an active subscription for this company account. Please cancel all subscriptions before proceeding with the company deletion.',
		// 				'You have an active subscription for this company account.',
		// 			confirmButtonText: 'Ok',
		// 			cancelButtonText: 'Cancel'
		// 		});
		// 		if (isConfirmed) {
		// 			deletionFinalNotification();
		// 			return;
		// 		}
		// 	}
		// 	return;
		// }
		deletionFinalNotification();
	};

	const confimrDeletion = async (): Promise<void> => {
		// TODO: check if there are otherCompanyUsers
		console.log('invitesList', invitesList);
		const otherCompanyUsers = acceptedInvitesList && acceptedInvitesList?.length > 0;
		let isConfirmed: boolean | FormData | null = null;
		if (!otherCompanyUsers) {
			isConfirmed = await confirmModal({
				title: 'Proceed with company deletion',
				message:
					// 'This action is irreversible. All users and integrations associated with this company will lose access.',
					'<span><input type="checkbox" id="confirm-delete" name="confirm-delete" value="confirm-delete" /> <label for="confirm-delete">This action is permanent. All company data, forecasts, team members, and historical records will be deleted. This cannot be undone.</label></span>',
				confirmButtonText: 'Yes, delete my company',
				confirmButtonColor: 'red',
				cancelButtonText: 'Cancel'
			});
		} else {
			isConfirmed = await confirmModal({
				title: 'Confirm removal of user access',
				message: [
					'There are still active users in this company. Deletion will permanently revoke their access and remove all user-linked data.',
					'click <a href="/manageUser?review=true">here</a> to see a list of active users for this company.',
					'<span><input type="checkbox" id="confirm-delete" name="confirm-delete" value="confirm-delete" /> <label for="confirm-delete">This action is permanent. All company data, forecasts, team members, and historical records will be deleted. This cannot be undone.</label></span>'
				],
				confirmButtonText: 'Yes, delete my company',
				confirmButtonColor: 'red',
				cancelButtonText: 'Cancel'
			});
		}
		if (isConfirmed) {
			const jsonObject: any = {};
			if (isConfirmed !== true) {
				(isConfirmed as FormData).forEach((value, key) => {
					jsonObject[key] = value;
				});
				// consider the user provided hard consent as the checkbox is checked

				// if (companyData?.company_id) {
				// 	const payload = { company_id: companyData?.company_id };
				// 	dispatch(deleteCompany(payload));
				// } else {
				// 	errorDeletion();
				// }
				checkForActiveSubscription();
				return;
			}
			// notify the user they must select the checkbox - checkbox is not checked
			notifyForCheckbox();
		}
	};

	const finishDownloadData = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Data export confirmation',
			message:
				'Your historical data has been successfully downloaded. You can now proceed with the Company deletion.',
			confirmButtonText: 'Proceed to delete company',
			cancelButtonText: 'Cancel'
		});
		if (isConfirmed) {
			confimrDeletion();
		}
	};

	const confirmDownloadData = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Trigger full data export',
			message:
				'Before deleting this company, would you like to download all historical data e.g. financials (active and archived), reports and users?',
			confirmButtonText: 'Download full data archive',
			cancelButtonText: 'Cancel'
		});
		if (isConfirmed) {
			const prepareList = [];
			if (financialsList) {
				prepareList.push({ data: financialsList, filename: 'financials.csv' });
			}
			if (invitesList) {
				prepareList.push({ data: invitesList, filename: 'invites.csv' });
			}
			downloadMultipleCSVsAsZip(prepareList);
			// TODO: Archive Timestamp & Compliance Record
			// •	System Logs: Export activity is logged under:
			// o	User ID
			// o	Timestamp
			// o	IP address
			// o	Data scope
			finishDownloadData();
		}
	};
	const confirmDashboardDownload = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Confirm Dashboard download',
			message: 'Would you like to download your Dashboards?',
			confirmButtonText: 'Yes, download my Dashboards',
			cancelButtonText: 'Cancel'
		});
		if (isConfirmed) {
			navigate('/dashboard');
			// there is data to download
		} else {
			confirmDownloadData();
		}
	};

	const confirmDeleteCompany = async (): Promise<void> => {
		console.log('delete company', financialsList, invitesList);
		const isConfirmed = await confirmModal({
			title: 'Prepare for deletion',
			message: 'moneyXplier® will automatically trigger a pre-deletion checklist.',
			confirmButtonText: 'Ok',
			cancelButtonText: 'Cancel'
		});
		if (isConfirmed) {
			if (
				(!financialsList || financialsList?.length === 0) &&
				(!invitesList || invitesList.length === 0)
			) {
				confimrDeletion();
				return;
			}
			// there is data to download
			confirmDashboardDownload();
		}
	};

	if (!companyData) {
		return <></>;
	}

	return (
		<>
			{displayAs === 'link' && (
				<a
					href="#"
					className={styles.deleteCompany}
					onClick={(e) => {
						e.preventDefault();
						if (!checkPermission()) return;
						confirmDeleteCompany();
					}}
					style={{ margin: '0px' }}
				>
					Delete Company
				</a>
			)}
			{displayAs === 'icon' && (
				<Button
					// className={styles.btn}
					style={{ color: '#5f5f5f' }}
					onClick={() => {
						if (!checkPermission()) return;
						confirmDeleteCompany();
					}}
					startIcon={<DeleteOutline />}
				/>
			)}
		</>
	);
};

export default DeleteCompany;
