/**
 * WordPress dependencies
 */
import apiFetch from '@safe-wordpress/api-fetch';
import { ToggleControl } from '@safe-wordpress/components';
import { useState } from '@safe-wordpress/element';
import { _x } from '@safe-wordpress/i18n';

export type ActiveControlProps = {
	readonly popupId: number;
	readonly initialValue: boolean;
	readonly disabled: boolean;
};

export const ActiveControl = ( {
	popupId,
	initialValue,
	disabled,
}: ActiveControlProps ): JSX.Element => {
	const { enabled, enable, isSynching } = useEnabled( popupId, initialValue );
	return (
		<ToggleControl
			{ ...{ disabled: disabled || isSynching } }
			label={
				<span className="screen-reader-text">
					{ _x( 'Activate popup', 'command', 'nelio-popups' ) }
				</span>
			}
			checked={ enabled }
			onChange={ ( value ) => void enable( value ) }
		/>
	);
};

// =======
// HELPERS
// =======

const useEnabled = ( popupId: number, initialValue: boolean ) => {
	const [ enabled, setEnabled ] = useState( initialValue );
	const [ isSynching, setSynching ] = useState( false );

	const enable = async ( value: boolean ) => {
		setSynching( true );
		try {
			const result = await apiFetch<
				{ readonly nelio_popups_is_enabled: boolean } | undefined
			>( {
				path: `/wp/v2/nelio_popup/${ popupId }`,
				method: 'POST',
				data: { nelio_popups_is_enabled: value },
			} );
			setEnabled( !! result?.nelio_popups_is_enabled );
		} catch ( error ) {
			setEnabled( enabled );
		}
		setSynching( false );
	};

	return { enabled, enable, isSynching };
};
