import { __ } from '@wordpress/i18n';
import { Button } from '@wordpress/components';
import { useCallback, useEffect, useState } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import useSWR from 'swr';

import Message from './Message';
import LianaMigrationModal from './LianaMigrationModal';
import useNotice from './useNotice';

type LianaMigrationProps = {
	endpoint: string;
	messageText?: string;
	refreshOnSave?: boolean;
	status: string;
};

const fetchLegacyData = async ( endpoint ) => {
	const data = await apiFetch( {
		url: `${ endpoint }`,
		headers: { 'Content-Type': 'application/json' },
	} );
	return data;
};

export default function Dashboard( props: LianaMigrationProps ) {
	const modalDismissed =
		localStorage.getItem( 'gs_migration_modal_dismissed' ) === '1';
	const { showNotice } = useNotice();
	const { endpoint, messageText = '', refreshOnSave = false } = props;
	const [ status, setstatus ] = useState( props.status );
	const [ modalOpen, setModalOpen ] = useState( ! modalDismissed );
	const [ migrationLoading, setMigrationLoading ] = useState( false );
	const { data, isLoading } = useSWR(
		status === 'not_started' ? endpoint : null,
		fetchLegacyData
	);

	// Update status if it changes in props.
	useEffect( () => {
		setstatus( props.status );
	}, [ props.status ] );

	const migrateLianaPlugins = useCallback( async () => {
		setMigrationLoading( true );
		try {
			const response = await apiFetch( {
				url: `${ endpoint }`,
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
			} );
			if ( response.success ) {
				if ( refreshOnSave ) {
					window.location.reload();
					return;
				}
				await setstatus( response.status );
				await setModalOpen( false );
			}
			showNotice(
				response.success ? 'success' : 'error',
				response.message
			);
		} catch ( error ) {
			// @ts-ignore
			showNotice( 'error', error.message );
		}
		setMigrationLoading( false );
	}, [ endpoint, refreshOnSave, showNotice ] );

	let migrationMessage: JSX.Element | null = null;
	if ( status === 'not_started' ) {
		const msgText = messageText
			? messageText
			: __(
					'GrowthStack now includes all features of the old Liana plugins. To prevent any conflicts, please deactivate those plugins and import their settings by clicking the Import settings button.',
					'liana-with-growthstack'
			  );
		migrationMessage = (
			<Message
				header="Old Liana plugins detected. Import settings from old plugins!"
				content={ msgText }
				button={
					<Button
						type="button"
						variant="primary"
						onClick={ () => setModalOpen( true ) }
					>
						{ __( 'Import settings', 'liana-with-growthstack' ) }
					</Button>
				}
				type="info"
			/>
		);
	}

	return (
		<>
			{ status === 'not_started' && (
				<LianaMigrationModal
					data={ data }
					dataIsLoading={ isLoading }
					loading={ migrationLoading }
					onClose={ () => setModalOpen( false ) }
					onMigrate={ migrateLianaPlugins }
					isOpen={ modalOpen }
				/>
			) }
			{ migrationMessage }
		</>
	);
}
