import { Button, BaseControl } from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';
import { __ } from '@wordpress/i18n';
import { openMediaLibrary } from './mediaUtils';

/**
 * Media (image) picker. By default stores the full media object; set
 * `field.returnFormat` to "url" (or "string") to store just the URL — useful
 * for plain VARCHAR columns (e.g. marker / category icons).
 */
const MediaField = ( { field, value, onChange } ) => {
	const returnsUrl =
		field?.returnFormat === 'url' || field?.returnFormat === 'string';

	// Normalise either a stored object or a stored URL string into an object
	// with a `.url` so the preview works in both modes.
	const mediaValue =
		value && typeof value === 'object'
			? value
			: typeof value === 'string' && value
			? { url: value }
			: null;

	const instanceId = useInstanceId( MediaField, 'media-field' );
	const controlId = field?.id ?? field?.name ?? instanceId;

	const handleSelect = ( media ) => {
		if ( returnsUrl ) {
			onChange( media?.url ?? null );
			return;
		}
		onChange( media ?? null );
	};

	const handleOpen = () => {
		openMediaLibrary( {
			field,
			value: mediaValue,
			onSelect: handleSelect,
		} );
	};

	return (
		<BaseControl
			id={ controlId }
			label={ field.label }
			help={ field.help }
			required={ field.required }
		>
			<div className="cliq-ui-media-field">
				<div className="cliq-ui-media-preview">
					{ mediaValue?.url ? (
						<img
							src={ mediaValue.url }
							alt={ mediaValue.alt ?? field.label ?? '' }
						/>
					) : (
						<span className="cliq-ui-media-placeholder">
							{ __( 'No image selected', 'cliq-store-locator' ) }
						</span>
					) }
				</div>
				<div className="cliq-ui-media-actions">
					<Button variant="secondary" onClick={ handleOpen }>
						{ mediaValue
							? __( 'Replace image', 'cliq-store-locator' )
							: __( 'Select image', 'cliq-store-locator' ) }
					</Button>
					{ mediaValue && (
						<Button
							variant="tertiary"
							onClick={ () => onChange( null ) }
						>
							{ __( 'Remove image', 'cliq-store-locator' ) }
						</Button>
					) }
				</div>
			</div>
		</BaseControl>
	);
};

export default MediaField;
