import { useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Thin wrapper around the native WordPress media library (`wp.media`).
 * This is WordPress core JS (loaded via `wp_enqueue_media()`), not part of
 * the `@wordpress/components` React library — it opens the same familiar
 * "Select or Upload Media" modal shop managers already know from products
 * and posts.
 */
export default function MediaPicker( { imageId, imageUrl, onSelect, onRemove } ) {
	const openLibrary = useCallback( () => {
		if ( ! window.wp || ! window.wp.media ) {
			return;
		}

		const frame = window.wp.media( {
			title: __( 'Select a gift wrap image', 'rt-gift-wrap-for-woocommerce' ),
			button: { text: __( 'Use this image', 'rt-gift-wrap-for-woocommerce' ) },
			library: { type: 'image' },
			multiple: false,
		} );

		frame.on( 'select', () => {
			const attachment = frame.state().get( 'selection' ).first().toJSON();
			onSelect( attachment.id, attachment.sizes?.thumbnail?.url || attachment.url );
		} );

		frame.open();
	}, [ onSelect ] );

	return (
		<div className="rtgw-media-picker">
			<div className="rtgw-media-picker__preview" onClick={ openLibrary } role="button" tabIndex={ 0 }>
				{ imageUrl ? (
					<img src={ imageUrl } alt="" />
				) : (
					<span className="rtgw-media-picker__placeholder">
						<svg width="22" height="22" viewBox="0 0 24 24" fill="none">
							<path
								d="M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6Z"
								stroke="currentColor"
								strokeWidth="1.5"
							/>
							<circle cx="9" cy="10" r="1.6" stroke="currentColor" strokeWidth="1.5" />
							<path d="M5 17l5-5 3 3 3-4 3 6" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
						</svg>
					</span>
				) }
			</div>
			<div className="rtgw-media-picker__actions">
				<button type="button" className="rtgw-media-picker__link" onClick={ openLibrary }>
					{ imageId ? __( 'Change image', 'rt-gift-wrap-for-woocommerce' ) : __( 'Choose image', 'rt-gift-wrap-for-woocommerce' ) }
				</button>
				{ !! imageId && (
					<button type="button" className="rtgw-media-picker__link rtgw-media-picker__link--danger" onClick={ onRemove }>
						{ __( 'Remove', 'rt-gift-wrap-for-woocommerce' ) }
					</button>
				) }
			</div>
		</div>
	);
}
