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

const GalleryField = ( { field, value, onChange } ) => {
	const galleryValue = Array.isArray( value ) ? value : [];
	const instanceId = useInstanceId( GalleryField, 'gallery-field' );
	const controlId = field?.id ?? field?.name ?? instanceId;

	const handleSelect = ( items ) => {
		onChange( items ?? [] );
	};

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

	const handleRemove = ( index ) => {
		const nextValue = galleryValue.filter(
			( _, itemIndex ) => itemIndex !== index
		);
		onChange( nextValue );
	};

	return (
		<BaseControl
			id={ controlId }
			label={ field.label }
			help={ field.help }
			required={ field.required }
		>
			<div className="cliq-ui-gallery-field">
				<div className="cliq-ui-gallery-thumbs">
					{ galleryValue.length === 0 && (
						<div className="cliq-ui-gallery-placeholder">
							{ __( 'No images selected yet.', 'cliq-store-locator' ) }
						</div>
					) }
					{ galleryValue.map( ( item, index ) => (
						<div
							className="cliq-ui-gallery-thumb"
							key={ item.id ?? index }
						>
							{ item?.url ? (
								<img
									src={ item.url }
									alt={ item.alt ?? field.label ?? '' }
								/>
							) : (
								<span className="cliq-ui-gallery-thumb-placeholder">
									{ __( 'No preview', 'cliq-store-locator' ) }
								</span>
							) }
							<button
								type="button"
								className="cliq-ui-gallery-thumb-remove"
								onClick={ () => handleRemove( index ) }
								aria-label={ __(
									'Remove image',
									'cliq-store-locator'
								) }
							>
								<X size={ 14 } />
							</button>
						</div>
					) ) }
				</div>
				<Button variant="secondary" onClick={ handleOpen }>
					{ galleryValue.length
						? __( 'Add more images', 'cliq-store-locator' )
						: __( 'Select images', 'cliq-store-locator' ) }
				</Button>
			</div>
		</BaseControl>
	);
};

export default GalleryField;
