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

import LianaAutomationSettings from './LianaAutomationSettings';
import LianaMigration from '../../shared/LianaMigration';
import LogViewer from './LogViewer';
import { handleMigration, nextAutomationFormStep } from '../utils';
import useNotice from '../../shared/useNotice';

type LianaAutomationTabProps = {
	channels: Array< any >;
	connected: boolean;
	cookieConsentPluginActive: boolean;
	formsPageUrl: string;
	migrationEndpoint: string;
	migrationStatus: string;
	restEndpoint: string;
	setChannels: ( channels: Array< any > ) => void;
	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 or saving any changes to GrowthStack's LianaAutomation integration will result in automated importing of the configurations from old plugins.",
	'liana-with-growthstack'
);

export default function LianaAutomationTab( props: LianaAutomationTabProps ) {
	const {
		channels,
		connected,
		cookieConsentPluginActive,
		formsPageUrl,
		migrationEndpoint,
		migrationStatus,
		restEndpoint,
		setChannels,
		setConnected,
		setMigrationStatus,
		setSettings,
		settings,
	} = props;

	const { showNotice } = useNotice();
	const [ step, setStep ] = useState(
		nextAutomationFormStep( {
			connected,
			settings,
		} )
	);

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

	const handleAutomationSave = 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 ) {
					setChannels( result.data.channels );
					setConnected( result.data.connected );
					setSettings( result.data.settings );
					setStep( ( prevStep ) => {
						const nextStep = nextAutomationFormStep( {
							connected: result.data.connected,
							prevStep,
							settings: result.data.settings,
						} );
						const queryRedirect = new URLSearchParams(
							window.location.search
						).get( 'redirect_after_save' );
						if ( nextStep === 0 && queryRedirect === 'forms' ) {
							window.location.href = formsPageUrl;
							return prevStep;
						}
						return nextStep;
					} );
				}
			} catch ( error: any ) {
				showNotice( 'error', error.message );
				if ( error.data ) {
					setChannels( error.data.channels );
					setConnected( error.data.connected );
					setSettings( error.data.settings );
				}
			}
			setLoading( false );
			setLogRefreshTrigger( ( prev ) => prev + 1 );
		},
		[
			restEndpoint,
			migrationStatus,
			migrationEndpoint,
			formsPageUrl,
			setChannels,
			setConnected,
			setSettings,
			setMigrationStatus,
			showNotice,
		]
	);

	const handleAutomationReset = useCallback( async () => {
		if (
			// eslint-disable-next-line no-alert
			! window.confirm(
				__(
					'Are you sure you want to reset LianaAutomation 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 );
				setStep( 1 );
			}
		} 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>{ __( 'LianaAutomation Settings', 'liana-with-growthstack' ) }</h2>
					<p>
						<a
							href="https://www.lianatech.com/solutions/marketing-automation/overview.html"
							target="_blank"
							rel="noreferrer"
						>
							LianaAutomation
						</a>{ ' ' }
						{ __(
							'is a marketing automation platform that enables you to create comprehensive customer profiles, build targeted segments, and set up dynamic workflows to deliver personalized messaging across multiple channels.',
							'liana-with-growthstack'
						) }
					</p>
				</div>
			</div>
			<LianaMigration
				endpoint={ migrationEndpoint }
				messageText={ migrationText }
				refreshOnSave={ true }
				status={ migrationStatus }
			/>
			<LianaAutomationSettings
				channels={ channels }
				connected={ connected }
				cookieConsentPluginActive={ cookieConsentPluginActive }
				loading={ loading }
				onReset={ handleAutomationReset }
				onSave={ handleAutomationSave }
				restEndpoint={ restEndpoint }
				setStep={ setStep }
				settings={ settings }
				step={ step }
			/>
			<LogViewer
				endpoint={ restEndpoint.replace( '/settings', '/logs' ) }
				refreshTrigger={ logRefreshTrigger }
			/>
		</>
	);
}
