import { __ } from '@wordpress/i18n';
import { Button, Modal, Spinner } from '@wordpress/components';

import Message from './Message';

type LianaMigrationModalProps = {
	data: object;
	dataIsLoading: boolean;
	isOpen: boolean;
	loading: boolean;
	onClose: () => void;
	onMigrate: () => void;
};

const dismissModal = ( onClose ) => {
	localStorage.setItem( 'gs_migration_modal_dismissed', '1' );
	onClose();
};

const getPluginsAsListItems = ( data ) => {
	if ( ! data || ! data.plugins ) {
		return null;
	}
	const plugins = data.plugins.automation.concat( data.plugins.mailer );
	return plugins.map( ( pluginName, index ) => (
		<li key={ index }>
			<strong>{ pluginName }</strong>
		</li>
	) );
};

export default function LianaMigrationModal( props: LianaMigrationModalProps ) {
	const {
		data = {},
		dataIsLoading,
		isOpen,
		loading,
		onClose,
		onMigrate,
	} = props;

	const modalContent = isOpen ? (
		<>
			<p>
				{ __(
					'The following plugins were detected on your site. We can automatically import settings and deactivate them to avoid conflicts.',
					'liana-with-growthstack'
				) }
			</p>
			<ul
				style={ {
					listStyle: 'disc',
					paddingLeft: '20px',
					marginBottom: '15px',
				} }
			>
				{ getPluginsAsListItems( data ) }
			</ul>
		</>
	) : null;

	return (
		<>
			{ isOpen && (
				<Modal
					title={ __(
						'Import settings from old Liana plugins',
						'liana-with-growthstack'
					) }
					onRequestClose={ () => dismissModal( onClose ) }
					style={ {
						width: '100%',
						maxWidth: '920px',
					} }
				>
					{ dataIsLoading && <Spinner /> }
					{ ! dataIsLoading && (
						<Message
							header={ __(
								'Old plugins detected',
								'liana-with-growthstack'
							) }
							layout="custom-content"
							type="info"
							content={ modalContent }
						/>
					) }
					<div className="gs-modal__actions">
						<Button
							variant="secondary"
							onClick={ () => dismissModal( onClose ) }
						>
							{ __( 'Cancel', 'liana-with-growthstack' ) }
						</Button>
						<Button
							disabled={ loading }
							variant="primary"
							onClick={ () => onMigrate() }
						>
							{ loading
								? __( 'Working…', 'liana-with-growthstack' )
								: __( 'Import settings', 'liana-with-growthstack' ) }
						</Button>
					</div>
				</Modal>
			) }
		</>
	);
}
