import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Alert, Button, Icon } from '../../shared/ui';

/**
 * Image chooser backed by the WordPress media library.
 * onPick: async () => void (opens the picker and stores the result); onClear removes the image.
 */
export default function ImageField({ label, url, onPick, onClear, hint }) {
	const [error, setError] = useState('');
	const pick = async () => {
		setError('');
		try {
			await onPick();
		} catch (e) {
			// Closing the media dialog without choosing is not an error.
			if (e && e.message && !/cancel|close/i.test(e.message)) setError(e.message);
		}
	};
	return (
		<div className="bp-field">
			<span className="bp-label">{label}</span>
			<div className="bp-imagefield">
				<div className="bp-imagefield__preview">{url ? <img src={url} alt="" /> : <Icon name="image" size={28} />}</div>
				<div className="bp-cluster">
					<Button variant="secondary" size="sm" icon="upload" onClick={pick}>
						{url ? __('Change image', 'pointly-booking') : __('Choose image', 'pointly-booking')}
					</Button>
					{url ? (
						<Button variant="ghost" size="sm" onClick={onClear}>
							{__('Remove', 'pointly-booking')}
						</Button>
					) : null}
				</div>
			</div>
			{hint ? <div className="bp-hint">{hint}</div> : null}
			{error ? <Alert tone="danger">{error}</Alert> : null}
		</div>
	);
}
