/**
 * Popup Builder Extension - Trigger Options Component
 */
import { useState, useEffect, useRef } from '@wordpress/element';
import { spectraClassNames } from '@spectra-helpers';
import {
	__experimentalToolsPanelItem as ToolsPanelItem,
	RangeControl,
	SelectControl,
	Dashicon
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';

// React Component to Render the Trigger Settings.
const TriggerOptions = ( props ) => {
	const {
		meta,
		setMeta,
		trigger,
		setTrigger,
		clientId
	} = props;

	// Set a constant for the clipboard based on whether this is a secure connection.
	const canUseClipboard = navigator.clipboard ? true : false;

	// Set Required States and Refs.
	const [ isCopied, setIsCopied ] = useState( false );
	const [ triggerDelay, setTriggerDelay ] = useState( meta['spectra-popup-trigger-delay'] || 0 );
	const triggerClassRef = useRef();

	// Update the trigger class ref when the trigger is changed.
	useEffect( () => {
		if ( canUseClipboard && triggerClassRef ) {
			triggerClassRef.current?.addEventListener( 'click', copyTriggerClass );
		}
		return () => {
			triggerClassRef.current?.removeEventListener( 'click', copyTriggerClass );
		} 
	}, [ trigger ] );

	// Update the trigger type meta.
	const updateTrigger = ( value ) => {
		setTrigger( value );
		setMeta( {
			...meta,
			'spectra-popup-trigger': value,
		} );
	}

	// Update the trigger delay meta.
	const updateTriggerDelay = ( value ) => {
		setTriggerDelay( value );
		setMeta( {
			...meta,
			'spectra-popup-trigger-delay': value,
		} );
	}

	// Copy the trigger class on click.
	const copyTriggerClass = () => {
		if ( !triggerClassRef.current ) return;
		
		triggerClassRef.current.style.pointerEvents = 'none';
		const hiddenInput = document.createElement( 'input' );

		hiddenInput.style.display = 'none';
		const postId = window.wp?.data?.select( 'core/editor' )?.getCurrentPostId() || 'unknown';
		hiddenInput.setAttribute( 'value', `spectra-popup-trigger-${ postId }` );
		document.body.appendChild( hiddenInput );

		hiddenInput.select();
		hiddenInput.setSelectionRange( 0, 99999 );
		navigator.clipboard.writeText( hiddenInput.value );

		setIsCopied( true );
		setTimeout( () => {
			document.body.removeChild( hiddenInput );
			setIsCopied( false );
			triggerClassRef.current.style.pointerEvents = '';
		}, 750 );
	}

	return (
		<>
			<ToolsPanelItem
				hasValue={ () => !! trigger }
				label={ __( 'Automatic Trigger Type', 'spectra-pro' ) }
				onDeselect={ () => updateTrigger( 'load' ) }
				resetAllFilter={ () => ( { trigger: 'load' } ) }
				isShownByDefault
				panelId={ clientId }
			>
				<SelectControl
					label={ __( 'Trigger Type', 'spectra-pro' ) }
					value={ trigger }
					options={ [
						{
							value: 'load',
							label: __( 'Load', 'spectra-pro' ),
						},
						{
							value: 'exit',
							label: __( 'Exit Intent', 'spectra-pro' ),
						},
						{
							value: 'element',
							label: __( 'Element Click', 'spectra-pro' ),
						},
					] }
					onChange={ updateTrigger }
				/>
			</ToolsPanelItem>
			{ ( 'load' === trigger ) && (
				<ToolsPanelItem
					hasValue={() => !!triggerDelay}
					label={__( 'Delay in Seconds', 'spectra-pro' ) }
					onDeselect={() => updateTriggerDelay( { triggerDelay: 0 } ) }
					isShownByDefault
					panelId={ clientId }
				>
					<RangeControl
						label={ __( 'Delay in Seconds', 'spectra-pro' ) }
						value={ triggerDelay }
						onChange={ ( value ) => updateTriggerDelay( value ) }
						min={ 0 }
						max={ 60 }
						step={ 1 }
						help={ __( 'Set delay between 0-60 seconds before popup appears on page load.', 'spectra-pro' ) }
					/>
				</ToolsPanelItem>
			) }
			{ ( 'element' === trigger ) && (
				<>
					<div className='spectra-popup__trigger-element-notice'>
					<p
						className={ spectraClassNames( [
							'spectra-popup__notice',
							canUseClipboard && 'spectra-popup__notice--clickable',
						] ) }
						ref={ triggerClassRef }
					>
						{ canUseClipboard && (
							<Dashicon
								icon='clipboard'
								style={ {
									color: isCopied ? '#007cba' : '',
								} }
							/>
						) }
						{ `spectra-popup-trigger-${ window.wp?.data?.select( 'core/editor' )?.getCurrentPostId() || 'unknown' }` }
					</p>
					<p className='spectra-popup__notice spectra-popup__notice--secondary'>
						{ __(
							'Copy and paste the class above to any block\'s Additional Classes to create a clickable element that will trigger the popup.',
							'spectra-pro',
						) }
					</p>
					</div>
				</>
			) }
		</>
	)
}

export default TriggerOptions;