import { __ } from '@wordpress/i18n';
import { useState, useCallback } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';

import LianaMailerSettings from './LianaMailerSettings';
import LianaMigration from '../../shared/LianaMigration';
import LogViewer from './LogViewer';
import { handleMigration } from '../utils';
import useNotice from '../../shared/useNotice';

type LianaMailerTabProps = {
	connected: boolean;
	formsPageUrl: string;
	migrationEndpoint: string;
	migrationStatus: string;
	restEndpoint: string;
	setConnected: ( connected: boolean ) => void;
	setMigrationStatus: ( status: string ) => void;
	setSettings: ( settings: any ) => void;
	settings: any;
};

const migrationText = __(
	"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. Activating GrowthStack's LianaMailer integration will result in automated importing of the configurations from old plugins.",
	'liana-with-growthstack'
);

export default function LianaMailerTab( props: LianaMailerTabProps ) {
	const {
		connected,
		formsPageUrl,
		migrationEndpoint,
		migrationStatus,
		restEndpoint,
		setConnected,
		setMigrationStatus,
		setSettings,
		settings,
	} = props;

	const { showNotice } = useNotice();

	const [ loading, setLoading ] = useState( false );
	const [ logRefreshTrigger, setLogRefreshTrigger ] = useState( 0 );

	const handleMailerSave = useCallback(
		async ( event: React.FormEvent< HTMLFormElement > ) => {
			event.preventDefault();
			const data = new FormData( event.currentTarget );
			setLoading( true );
			try {
				// Gather JSON of form data
				const json = JSON.stringify(
					Object.fromEntries( data.entries() )
				);
				const result = await apiFetch( {
					url: restEndpoint,
					body: json,
					headers: {
						'Content-Type': 'application/json',
					},
					method: 'POST',
				} );
				showNotice(
					result.success ? 'success' : 'error',
					result.message
				);
				if ( migrationStatus === 'not_started' && result.success ) {
					const migration =
						await handleMigration( migrationEndpoint );
					setMigrationStatus( migration.status );
					showNotice(
						migration.success ? 'success' : 'error',
						migration.message
					);
				}
				if ( result.data ) {
					setSettings( result.data.settings );
					setConnected( result.data.connected );
					const queryRedirect = new URLSearchParams(
						window.location.search
					).get( 'redirect_after_save' );
					if ( result.data.connected && queryRedirect === 'forms' ) {
						window.location.href = formsPageUrl;
					}
				}
			} catch ( error: any ) {
				showNotice( 'error', error.message );
				if ( error.data ) {
					setSettings( error.data.settings );
					setConnected( error.data.connected );
				}
			}
			setLoading( false );
			setLogRefreshTrigger( ( prev ) => prev + 1 );
		},
		[
			restEndpoint,
			migrationStatus,
			migrationEndpoint,
			formsPageUrl,
			setSettings,
			setConnected,
			setMigrationStatus,
			showNotice,
		]
	);

	const handleMailerReset = useCallback( async () => {
		if (
			// eslint-disable-next-line no-alert
			! window.confirm(
				__(
					'Are you sure you want to reset LianaMailer settings? This action cannot be undone.',
					'liana-with-growthstack'
				)
			)
		) {
			return;
		}
		setLoading( true );
		try {
			const result = await apiFetch( {
				url: `${ restEndpoint }/reset`,
				method: 'DELETE',
			} );
			showNotice( result.success ? 'success' : 'error', result.message );
			if ( result.data ) {
				setSettings( result.data.settings );
				setConnected( result.data.connected );
			}
		} catch ( error: any ) {
			showNotice( 'error', error.message );
		}
		setLoading( false );
	}, [ restEndpoint, showNotice, setSettings, setConnected ] );

	return (
		<>
			<div className="gs-header-box">
				<div className="gs-header-box__main">
					<h2>{ __( 'LianaMailer Settings', 'liana-with-growthstack' ) }</h2>
					<p>
						<a
							href="https://www.lianatech.com/solutions/email-marketing/overview.html"
							target="_blank"
							rel="noreferrer"
						>
							LianaMailer
						</a>{ ' ' }
						{ __(
							'is an email marketing platform that offers comprehensive tools for creating, sending, and reporting on targeted email campaigns to effectively engage your subscriber base.',
							'liana-with-growthstack'
						) }
					</p>
				</div>
			</div>
			<LianaMigration
				endpoint={ migrationEndpoint }
				messageText={ migrationText }
				refreshOnSave={ true }
				status={ migrationStatus }
			/>
			<LianaMailerSettings
				connected={ connected }
				loading={ loading }
				onReset={ handleMailerReset }
				onSave={ handleMailerSave }
				restEndpoint={ restEndpoint }
				settings={ settings }
			/>
			<LogViewer
				endpoint={ restEndpoint.replace( '/settings', '/logs' ) }
				refreshTrigger={ logRefreshTrigger }
			/>
		</>
	);
}
