import {useState, useEffect} from '@wordpress/element';
import {__} from '@wordpress/i18n';
import Button from '../components/Button';
import '../scss/_image_upload.scss';

const ImageUploadField = ( {field, value, onChange} ) => {
	const [previewUrl, setPreviewUrl] = useState( '' );
	const [isLoading, setIsLoading] = useState( false );

	useEffect( () => {
		const imageId = parseInt( value, 10 );

		if ( imageId && imageId > 0 ) {
			setIsLoading( true );
			wp.apiFetch( {path: `/wp/v2/media/${imageId}`} )
			  .then( media => {
				  const thumbnailUrl = media.media_details?.sizes?.thumbnail?.source_url || media.source_url;
				  setPreviewUrl( thumbnailUrl );
			  } )
			  .catch( error => {
				  console.error( 'Could not fetch image preview:', error );
				  setPreviewUrl( '' );
			  } )
			  .finally( () => {
				  setIsLoading( false );
			  } );
		} else {
			setPreviewUrl( '' );
		}
	}, [value] );

	const openMediaLibrary = () => {
		const frame = wp.media( {
			title:    __( 'Select Image', 'adpresso' ),
			button:   {text: __( 'Use this image', 'adpresso' )},
			multiple: false
		} );

		frame.on( 'select', () => {
			const attachment = frame.state().get( 'selection' ).first().toJSON();
			onChange( field.id, attachment.id );
		} );

		frame.open();
	};

	return (
		<div className="adpresso-image-upload-wrapper">
			<div className="adpresso-image-preview">
				{isLoading && <span className="spinner is-active"></span>}
				{!isLoading && previewUrl ? (
					<img src={previewUrl} alt={__( 'Image preview', 'adpresso' )}/>
				) : (
					!isLoading && <div className="adpresso-image-placeholder">{__( 'No image selected', 'adpresso' )}</div>
				)}
			</div>
			<div className="adpresso-image-upload-actions">
				<Button variant="primary" className="adpresso-btn adpresso-btn-action" onClick={openMediaLibrary}>
					{__( 'Select Image', 'adpresso' )}
				</Button>
				{value > 0 && (
					<Button
						variant="destructive"
						className="adpresso-btn adpresso-btn-action"
						isDestructive
						onClick={() => onChange( field.id, 0 )}
					>
						{__( 'Remove Image', 'adpresso' )}
					</Button>
				)}
			</div>
		</div>
	);
};

export default ImageUploadField;
