import type { FormEvent } from 'react';
import type { CompanyDbModel } from '../../../Companies/Components/CompaniesComponents.helper';
import { useUiContext } from '../../../../Store/UiContext/UiContext';
/* eslint-disable import/no-cycle */
import { useNavigate, Link } from 'react-router-dom';
import styles from './DeleteAccount.module.scss';
import type { UserModel } from '../../../../Store/User/user-context.helper';
import Button from '../../../../Components/UI/Button/Button';
import { useDispatch } from 'react-redux';
import { deleteEmptyUserAccount } from '../../../../ReduxState/login/loginSlice';
import type { AppDispatch } from '../../../../ReduxState/store';

const DeleteAccount = ({
	selectedUser,
	allCompanyData,
	companyData,
	displayAs = 'link'
}: {
	selectedUser: UserModel | null | undefined;
	allCompanyData?: CompanyDbModel[] | null | undefined;
	companyData: CompanyDbModel[] | null | undefined;
	displayAs?: 'link' | 'icon' | 'button';
}): JSX.Element => {
	const { confirmModal } = useUiContext();
	const navigate = useNavigate();
	const dispatch = useDispatch<AppDispatch>();

	const getMyCompanies = (): CompanyDbModel[] | undefined => {
		console.log('companyData', companyData);
		console.log('selectedUser', selectedUser);
		return companyData?.filter(
			(company) => !company.owner || company.owner._id === selectedUser?._id
		);
	};

	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 (backTo = 'default'): 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) {
			if (backTo === 'default') {
				deleteSubscriber();
			} else {
				explicitDeleteAccountConfirmation();
			}
		}
	};

	const explicitDeleteAccountConfirmation = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Confirm account deletion',
			message: [
				'Deleting your moneyXplier account will remove your access permanently. Your data and saved settings will be deleted. This action is irreversible.',
				'<span><input type="checkbox" id="confirm-delete" name="confirm-delete" value="confirm-delete" /> <label for="confirm-delete">I understand this action is permanent</label></span>'
			],
			confirmButtonText: 'Confirm Deletion',
			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

				dispatch(deleteEmptyUserAccount({ user: selectedUser }));
				return;
			}
			// notify the user they must select the checkbox - checkbox is not checked
			notifyForCheckbox('explicitDeleteAccountConfirmation');
		}
	};

	const deleteAccount = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'What happens when you delete your account?',
			message:
				'When you delete your account, we permanently erase all personally identifiable data, including your name, email, profile, connected company records, and account history.<br/><br/>We may retain certain anonymised or aggregated usage data for analytical and product improvement purposes, which can no longer be linked to you. 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.<br/><br/>Please note that this process is irreversible.',
			confirmButtonText: 'Yes, I understand – delete permanently',
			cancelButtonText: 'Cancel'
		});
		if (isConfirmed) {
			explicitDeleteAccountConfirmation();
		} else {
			// do nothing
		}
	};

	const finalDeleteConfirmation = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Data usage',
			message:
				'Your subscription and all associated company data will now be deleted. This action is irreversible',
			confirmButtonText: 'Confirm'
		});

		if (isConfirmed) {
			// TODO: Actually delete the data
			// eslint-disable-next-line no-alert
			alert('TODO: Actually delete the data');
		} else {
			// do nothing
		}
	};

	const consentForDataUsage = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Data usage',
			message:
				'Before deleting your subscription, can we use your company data for anonymous research',
			confirmButtonText: 'Yes',
			cancelButtonText: 'No'
		});

		if (isConfirmed) {
			// TODO:Anonymize the data
			// eslint-disable-next-line no-alert
			alert('TODO: Anonymize the data');
		}
		// but always proceed with final confirmation
		finalDeleteConfirmation();
	};

	const confirmDeleteSubscription = async (): Promise<void> => {
		// proceed with delete process
		const isConfirmed = await confirmModal({
			title: 'Do you really want to delete your account?',
			message:
				'You have active subscriptions. Before deleting your account you must delete all your companies (including ones with demo access) from companies management screen',
			confirmButtonText: 'Yes, take me to management companies',
			cancelButtonText: 'Cancel'
		});

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

	const confirmTransferAccount = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Confirm account deletion',
			message:
				'To delete your moneyXplier® account, you must first transfer company ownership and subscription.<br /><br />Do you wish to proceed with the transfer — or delete your account without transferring the company?',
			confirmButtonText: 'Transfer',
			cancelButtonText: 'Delete without transfer'
		});
		if (isConfirmed) {
			// no longer display transfer account screen
			// navigate('/personal-account/transfer');
			// take users to manage users screen
			navigate('/manageUser?transfer=true');
		} else {
			confirmDeleteSubscription();
		}
	};

	const secondConfirmDeleteWithoutTransfer = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Are you sure you want to delete your account?',
			message: [
				"To proceed with the self-deletion of your moneyXplier account you must first delete all your Companies and remove all associated companies' access. Do you wish to proceed?"
			],
			confirmButtonText: 'Yes, Delete my companies',
			cancelButtonText: 'Cancel'
		});
		if (isConfirmed) {
			navigate('/companySettings?initiatedByDelete=true');
		}
	};

	const confirmDeleteWithoutTransfer = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Are you sure you want to delete your account?',
			message: [
				'We are sorry to see you go. Deleting your account is a permanent action and it cannot be undone.'
			],
			confirmButtonText: 'Delete',
			cancelButtonText: 'Cancel'
		});
		if (isConfirmed) {
			secondConfirmDeleteWithoutTransfer();
		}
	};

	const deleteWithoutTransfer = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Are you sure you want to delete your account?',
			message: [
				'Deleting your account without transferring ownership will leave the company without an active owner.',
				'<p>This may result in:</p>',
				'<ul><li>Team members losing access</li><li>Forecast data being orphaned</li><li>Active subscriptions requiring manual support resolution</li>',
				'Are you sure you want to continue?'
			],
			confirmButtonText: 'Yes, delete anyway',
			cancelButtonText: 'Cancel'
		});
		if (isConfirmed) {
			confirmDeleteWithoutTransfer();
		}
	};

	const deleteSubscriber = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Confirm account deletion',
			message: [
				'To self-delete your moneyXplier® account you must first transfer company ownership and subscription to another user within your Company with Admin access.<br /><br />Do you wish to proceed with transfer?'
				// '<input type="checkbox" id="confirm-delete" name="confirm-delete" value="confirm-delete" /> <label for="confirm-delete">Confirm deletion</label>'
			],
			thirdButtonText: 'Transfer',
			confirmButtonText: 'Delete without transfer',
			cancelButtonText: 'Cancel'
		});

		if (isConfirmed) {
			// console.log('isConfirmed', Object.fromEntries((isConfirmed as FormData).entries()));
			if (isConfirmed === true) {
				// this means essentially second button was pressed which is delete without transfer
				deleteWithoutTransfer();
				return;
			}
			// const otherCompanyUsers = true; // TODO: actually check if there are other users in the company
			// if (otherCompanyUsers) {
			// confirmTransferAccount();
			navigate('/manageUser?transfer=true');
			// } else {
			// 	confirmDeleteSubscription();
			// }
			// return;
			// 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

			// 	// 1st: check if there are other users in the company
			// 	// NOTE: Only users with relevant permissions (e.g., administrators or users with subscription rights) can be selected for the transfer
			// 	const otherCompanyUsers = true; // TODO: actually check if there are other users in the company
			// 	if (otherCompanyUsers) {
			// 		confirmTransferAccount();
			// 	} else {
			// 		confirmDeleteSubscription();
			// 	}
			// 	return;
			// }
			// // notify the user they must select the checkbox - checkbox is not checked
			// notifyForCheckbox();
		}
	};

	const confirmSelfDeleteActiveInvitee = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Are you sure you want to delete your account?',
			message:
				"To proceed with self-deletion of your moneyXplier user account you must first request removal of all associated companies' access.  Do you wish to proceed?",
			confirmButtonText: 'Yes, Delete',
			cancelButtonText: 'Cancel'
		});

		if (isConfirmed) {
			navigate('/personal-account/my-active-invites');
		}
	};

	const deleteActiveInvitee = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Are you sure you want to delete your account?',
			message:
				'We are sorry to see you go. Deleting your account is a permanent action and it cannot be undone.',
			confirmButtonText: 'Delete',
			cancelButtonText: 'Cancel'
		});

		if (isConfirmed) {
			confirmSelfDeleteActiveInvitee();
		}
	};

	const deleteInvitee = async (): Promise<void> => {
		const isConfirmed = await confirmModal({
			title: 'Confirm account deletion',
			message:
				'To delete your account, you must be removed from all companies where you are invited!',
			confirmButtonText: 'Show companies where invited',
			cancelButtonText: 'Cancel'
		});

		if (isConfirmed) {
			// 1st: check if there are other users in the company
			// NOTE: Only users with relevant permissions (e.g., administrators or users with subscription rights) can be selected for the transfer
			const otherCompanyUsers = true; // TODO: actually check if there are other users in the company
			if (otherCompanyUsers) {
				// confirmShowCompniesWhereInvited();
				navigate('/personal-account/my-active-invites');
			}
		}
	};

	const deleteHandler = async (event: FormEvent): Promise<void> => {
		event.preventDefault();
		console.log('Company data', companyData, 'allCompanyData', allCompanyData);
		// determine type of delete
		if (
			(!companyData || companyData.length === 0) &&
			allCompanyData &&
			allCompanyData.length >= 0
		) {
			// deleteInvitee();
			deleteAccount();
			return;
		}

		const myCompanies = getMyCompanies();

		if (myCompanies && myCompanies.length > 0) {
			deleteSubscriber();
		} else {
			deleteActiveInvitee();
		}
	};

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

	return (
		<>
			{displayAs === 'link' && (
				<Link className={styles.deleteAccount} to="deleteAccount" onClick={deleteHandler}>
					Delete account
				</Link>
			)}
			{displayAs === 'icon' && (
				<button className={`${styles.revokeButton}`} onClick={deleteHandler} title="revoke access">
					<svg
						width="12"
						height="12"
						viewBox="0 0 12 12"
						fill="none"
						xmlns="http://www.w3.org/2000/svg"
					>
						<path
							d="M10.8482 0.949747C11.0123 1.11384 11.1045 1.3364 11.1045 1.56847C11.1045 1.80053 11.0123 2.02309 10.8482 2.18718L7.13587 5.89949L10.8482 9.61181C11.0123 9.7759 11.1045 9.99846 11.1045 10.2305C11.1045 10.4626 11.0123 10.6851 10.8482 10.8492C10.6841 11.0133 10.4615 11.1055 10.2295 11.1055C9.9974 11.1055 9.77484 11.0133 9.61075 10.8492L5.89844 7.13693L2.18613 10.8492C2.02203 11.0133 1.79947 11.1055 1.56741 11.1055C1.33534 11.1055 1.11278 11.0133 0.94869 10.8492C0.784596 10.6851 0.692408 10.4626 0.692408 10.2305C0.692408 9.99846 0.784596 9.7759 0.94869 9.61181L4.661 5.89949L0.94869 2.18718C0.784596 2.02309 0.692408 1.80053 0.692408 1.56847C0.692408 1.3364 0.784596 1.11384 0.94869 0.949747C1.11278 0.785653 1.33534 0.693466 1.56741 0.693466C1.79947 0.693466 2.02203 0.785653 2.18613 0.949747L5.89844 4.66206L9.61075 0.949747C9.77484 0.785653 9.9974 0.693466 10.2295 0.693466C10.4615 0.693466 10.6841 0.785653 10.8482 0.949747Z"
							fill="#5F5F5F"
						/>
					</svg>
				</button>
			)}
			{displayAs === 'button' && (
				<Button
					id="deleteAccount"
					link=""
					onClick={deleteHandler}
					type="submit"
					value="Delete my user account"
				/>
			)}
		</>
	);
};

export default DeleteAccount;
