import { __ } from '@wordpress/i18n';
import { Button, Icon, SelectControl } from '@wordpress/components';
import { useEffect, useMemo, useState } from '@wordpress/element';
import { linkOff } from '@wordpress/icons';

import ConnectionStatus from './ConnectionStatus';
import LianaAPIFields from './LianaAPIFields';
import Steps from '../../shared/Steps';
import steps from './automationSteps';
import AutomationTogglerFields from './AutomationTogglerFields';
import { makeOptionsOfChannels } from '../utils';

type LianaAutomationSettingsProps = {
	channels: Array< { id: string; name: string } >;
	connected: boolean;
	cookieConsentPluginActive: boolean;
	loading: boolean;
	onReset: () => void;
	onSave: ( event: React.FormEvent< HTMLFormElement > ) => void;
	restEndpoint: string;
	setStep: ( updater: ( prevStep: number ) => number ) => void;
	settings: LianaAutomationSettings;
	step: number;
};

export default function LianaAutomationSettings(
	props: LianaAutomationSettingsProps
) {
	const {
		channels,
		connected,
		cookieConsentPluginActive,
		loading,
		onReset,
		onSave,
		restEndpoint,
		setStep,
		settings,
		step,
	} = props;

	const [ stateSettings, setStateSettings ] = useState( settings );

	// Sync stateSettings when props.settings changes on save
	useEffect( () => {
		setStateSettings( settings );
	}, [ settings ] );

	const onInputChange = ( name: string, value: string | boolean ) => {
		// Update the state or perform any action on input change
		const [ prefix, key ] = name.split( '_' );
		setStateSettings( ( prevSettings ) => {
			return {
				...prevSettings,
				[ prefix ]: {
					...prevSettings[ prefix ],
					[ key ]: value,
				},
			};
		} );
	};

	const defaultChannelOptions = useMemo(
		() =>
			makeOptionsOfChannels( channels, {
				value: '',
				label: __( 'Select a channel', 'liana-with-growthstack' ),
			} ),
		[ channels ]
	);

	const channelOptions = useMemo(
		() =>
			makeOptionsOfChannels( channels, {
				value: 'default',
				label: __( 'Default channel', 'liana-with-growthstack' ),
			} ),
		[ channels ]
	);

	let submitButtonText = __( 'Save Settings', 'liana-with-growthstack' );
	if ( loading ) {
		submitButtonText = __( 'Saving…', 'liana-with-growthstack' );
	} else if ( step === 1 || step === 2 ) {
		submitButtonText = __( 'Continue', 'liana-with-growthstack' );
	}

	return (
		<>
			{ step > 0 && <Steps active={ step } steps={ steps } /> }
			<div className="gs-box">
				<form
					className="gs-settings-form"
					method="post"
					action={ restEndpoint }
					onSubmit={ onSave }
				>
					{ ( step === 0 || step === 1 ) && (
						<div className="gs-flex gs-flex--justify-between gs-flex--align-start">
							{ step === 0 && (
								<div>
									<h2 className="gs-box__title">
										{ __(
											'LianaAutomation API Settings',
											'liana-with-growthstack'
										) }
									</h2>
									<p className="gs-box__desc">
										<ConnectionStatus
											connected={ connected }
											settings={ settings.api }
										/>
									</p>
								</div>
							) }
							{ step === 1 && (
								<p>
									{ __(
										'Request your API credentials from ',
										'liana-with-growthstack'
									) }
									<a href="mailto:support@lianatech.com">
										{ __(
											"Liana's support",
											'liana-with-growthstack'
										) }
									</a>
								</p>
							) }
							<Button
								disabled={ loading }
								icon={ linkOff }
								onClick={ onReset }
								type="button"
								variant="tertiary"
							>
								{ __( 'Reset', 'liana-with-growthstack' ) }
							</Button>
						</div>
					) }
					<input type="hidden" name="step" value={ step } />
					{ ( step === 0 || step === 1 ) && (
						<LianaAPIFields
							namePrefix="api_"
							onInputChange={ onInputChange }
							values={ stateSettings.api }
						/>
					) }

					{ step === 0 && (
						<h3>
							{ __(
								'Tracking options',
								'liana-with-growthstack'
							) }
						</h3>
					) }

					{ ( step === 0 || step === 2 ) && (
						<SelectControl
							className="gs-select-control"
							name="channel_id"
							label={
								__(
									'Default channel',
									'liana-with-growthstack'
								) + ' *'
							}
							value={ stateSettings.channel.id }
							onChange={ ( value ) =>
								onInputChange( 'channel_id', value )
							}
							options={ defaultChannelOptions }
							required
							variant="minimal"
						/>
					) }

					{ ( step === 0 || step === 3 ) && (
						<AutomationTogglerFields
							channelOptions={ channelOptions }
							cookieConsentPluginActive={ cookieConsentPluginActive }
							onInputChange={ onInputChange }
							step={ step }
							values={ stateSettings.channel }
						/>
					) }

					<div className="gs-submit-container">
						{ step > 1 && (
							<Button
								disabled={ loading }
								onClick={ () =>
									setStep( ( prevStep ) => prevStep - 1 )
								}
								type="button"
								variant="secondary"
							>
								<Icon icon="arrow-left-alt" />
								{ __( 'Go back', 'liana-with-growthstack' ) }
							</Button>
						) }
						<Button
							disabled={
								loading
							}
							type="submit"
							variant="primary"
						>
							{ submitButtonText }
							{ step > 0 && step < 3 && (
								<Icon icon="arrow-right-alt" />
							) }
						</Button>
					</div>
				</form>
			</div>
		</>
	);
}
