import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import FieldControl from '../components/FieldControl';
import Button from '../components/Button';

/**
 * Read-only Slot ID + embed-snippet display for the Headless placement type.
 *
 * @param field
 * @param entityData
 */
const SlotInfoField = ( { field, entityData } ) => {
	const [ copied, setCopied ] = useState( false );
	const { slug = '', saved = false } = entityData?.slot_info || {};
	const snippet = `<adpresso-slot slot-id="${ slug }"></adpresso-slot>`;

	const handleCopy = () => {
		navigator.clipboard.writeText( snippet );
		setCopied( true );
		setTimeout( () => setCopied( false ), 2000 );
	};

	return (
		<FieldControl
			label={ field.label }
			help={ field.description }
			id={ field.id }
		>
			{ ! saved || ! slug ? (
				<p>
					{ __(
						'Save this placement to get its Slot ID.',
						'adpresso'
					) }
				</p>
			) : (
				<>
					<p>
						<strong>{ __( 'Slot ID', 'adpresso' ) }:</strong>{ ' ' }
						<code className="adpresso-code">{ slug }</code>
					</p>
					<p>
						<strong>{ __( 'Embed snippet', 'adpresso' ) }:</strong>
					</p>
					<div
						style={ {
							display: 'flex',
							alignItems: 'center',
							gap: '8px',
						} }
					>
						<code className="adpresso-code" style={ { flex: 1 } }>
							{ snippet }
						</code>
						<Button variant="action" onClick={ handleCopy }>
							{ copied
								? __( 'Copied!', 'adpresso' )
								: __( 'Copy', 'adpresso' ) }
						</Button>
					</div>
				</>
			) }
		</FieldControl>
	);
};

export default SlotInfoField;
