/**
 * GoValid QR Code block.
 *
 * @package GoValid_QR
 */

( function ( blocks, element, blockEditor, components, i18n, apiFetch ) {
	var el             = element.createElement;
	var Fragment       = element.Fragment;
	var useState       = element.useState;
	var useEffect      = element.useEffect;
	var InspectorControls = blockEditor.InspectorControls;
	var useBlockProps   = blockEditor.useBlockProps;
	var PanelBody      = components.PanelBody;
	var TextControl    = components.TextControl;
	var RangeControl   = components.RangeControl;
	var ToggleControl  = components.ToggleControl;
	var Button         = components.Button;
	var Modal          = components.Modal;
	var Spinner        = components.Spinner;
	var __             = i18n.__;

	blocks.registerBlockType( 'govalid-qr/qr-code', {
		edit: function ( props ) {
			var attributes    = props.attributes;
			var setAttributes = props.setAttributes;
			var blockProps    = useBlockProps();

			var _modalState  = useState( false );
			var isModalOpen  = _modalState[0];
			var setModalOpen = _modalState[1];

			var _qrState = useState( [] );
			var qrCodes  = _qrState[0];
			var setQRCodes = _qrState[1];

			var _loadingState = useState( false );
			var isLoading     = _loadingState[0];
			var setLoading    = _loadingState[1];

			var _searchState = useState( '' );
			var searchTerm   = _searchState[0];
			var setSearchTerm = _searchState[1];

			var _previewState = useState( null );
			var previewData   = _previewState[0];
			var setPreviewData = _previewState[1];

			// Fetch QR detail for preview when ID is set.
			useEffect( function () {
				if ( ! attributes.qrId ) {
					setPreviewData( null );
					return;
				}
				apiFetch( { path: '/govalid-qr/v1/qr-codes/' + attributes.qrId } )
					.then( function ( data ) { setPreviewData( data ); } )
					.catch( function () { setPreviewData( null ); } );
			}, [ attributes.qrId ] );

			// Fetch QR list for picker modal.
			function openPicker() {
				setModalOpen( true );
				setLoading( true );
				apiFetch( { path: '/govalid-qr/v1/qr-codes?per_page=50' } )
					.then( function ( data ) {
						var results = data.results || data;
						setQRCodes( Array.isArray( results ) ? results : [] );
						setLoading( false );
					} )
					.catch( function () {
						setQRCodes( [] );
						setLoading( false );
					} );
			}

			function selectQR( qr ) {
				setAttributes( {
					qrId: qr.uuid || qr.id || '',
					qrName: qr.name || '',
				} );
				setModalOpen( false );
			}

			// Filter QR codes by search.
			var filteredCodes = qrCodes.filter( function ( qr ) {
				if ( ! searchTerm ) return true;
				var name = ( qr.name || '' ).toLowerCase();
				return name.indexOf( searchTerm.toLowerCase() ) !== -1;
			} );

			// Render block content.
			var content;
			if ( ! attributes.qrId ) {
				content = el( 'div', { className: 'govalid-qr-placeholder-block' },
					el( 'p', null, __( 'No QR code selected.', 'govalid-qr' ) ),
					el( Button, { variant: 'primary', onClick: openPicker },
						__( 'Select QR Code', 'govalid-qr' )
					)
				);
			} else if ( previewData && previewData.image_url ) {
				content = el( 'div', { style: { textAlign: attributes.alignment } },
					el( 'img', {
						src: previewData.image_url,
						alt: attributes.qrName,
						width: attributes.width,
						height: attributes.width,
						className: 'govalid-qr-preview-image',
					} ),
					attributes.showLabel && attributes.qrName
						? el( 'p', { className: 'govalid-qr-label' }, attributes.qrName )
						: null
				);
			} else {
				content = el( 'div', { className: 'govalid-qr-placeholder-block' },
					el( 'p', null, attributes.qrName || __( 'Loading QR code...', 'govalid-qr' ) ),
					el( Button, { variant: 'secondary', onClick: openPicker, isSmall: true },
						__( 'Change QR Code', 'govalid-qr' )
					)
				);
			}

			return el( Fragment, null,
				el( InspectorControls, null,
					el( PanelBody, { title: __( 'QR Code Settings', 'govalid-qr' ) },
						el( 'div', { className: 'govalid-qr-selected' },
							attributes.qrId
								? el( 'p', null,
									el( 'strong', null, __( 'Selected: ', 'govalid-qr' ) ),
									attributes.qrName || attributes.qrId
								)
								: el( 'p', null, __( 'No QR code selected.', 'govalid-qr' ) )
						),
						el( Button, {
							variant: 'secondary',
							onClick: openPicker,
							isSmall: true,
							style: { marginBottom: '16px' },
						}, attributes.qrId
							? __( 'Change QR Code', 'govalid-qr' )
							: __( 'Select QR Code', 'govalid-qr' )
						),
						el( RangeControl, {
							label: __( 'Width (px)', 'govalid-qr' ),
							value: attributes.width,
							onChange: function ( v ) { setAttributes( { width: v } ); },
							min: 50,
							max: 600,
							step: 10,
						} ),
						el( ToggleControl, {
							label: __( 'Show Label', 'govalid-qr' ),
							checked: attributes.showLabel,
							onChange: function ( v ) { setAttributes( { showLabel: v } ); },
						} )
					)
				),
				el( 'div', blockProps, content ),
				isModalOpen && el( Modal, {
					title: __( 'Select a QR Code', 'govalid-qr' ),
					onRequestClose: function () { setModalOpen( false ); },
					className: 'govalid-qr-picker-modal',
				},
					el( TextControl, {
						placeholder: __( 'Search QR codes...', 'govalid-qr' ),
						value: searchTerm,
						onChange: setSearchTerm,
					} ),
					isLoading
						? el( Spinner, null )
						: filteredCodes.length === 0
							? el( 'p', null, __( 'No QR codes found.', 'govalid-qr' ) )
							: el( 'div', { className: 'govalid-qr-picker-list' },
								filteredCodes.map( function ( qr ) {
									return el( 'button', {
										key: qr.uuid || qr.id,
										className: 'govalid-qr-picker-item',
										onClick: function () { selectQR( qr ); },
										type: 'button',
									},
										qr.image_url
											? el( 'img', {
												src: qr.image_url,
												alt: qr.name,
												width: 48,
												height: 48,
											} )
											: null,
										el( 'span', { className: 'govalid-qr-picker-name' }, qr.name || qr.uuid )
									);
								} )
							)
				)
			);
		},

		save: function () {
			// Dynamic block — rendered server-side.
			return null;
		},
	} );
} )(
	window.wp.blocks,
	window.wp.element,
	window.wp.blockEditor,
	window.wp.components,
	window.wp.i18n,
	window.wp.apiFetch
);
