/* global wp */
( function() {
	const { registerBlockType } = wp.blocks;
	const { __, setLocaleData } = wp.i18n;
	// Include BlockControls to add toolbar actions in the block editor
	const { useBlockProps, InspectorControls, BlockControls } = wp.blockEditor || wp.editor;
	// Include Toolbar components for editor toolbar buttons
	const { PanelBody, ToggleControl, SelectControl, SearchControl, Placeholder, Spinner, Button, ToolbarGroup, ToolbarButton } = wp.components;
	const { useState, useEffect } = wp.element;
	const apiFetch = wp.apiFetch;

	// Hydrate locale data when provided by PHP as a fallback.
	if ( window.wcAppointmentsAppointmentFormLocaleData ) {
		setLocaleData( window.wcAppointmentsAppointmentFormLocaleData, 'woocommerce-appointments' );
	}

	registerBlockType( 'woocommerce-appointments/appointment-form', {
		title: __( 'Appointment Form', 'woocommerce-appointments' ),
		description: __( 'Render the appointment form for a product.', 'woocommerce-appointments' ),
		category: 'woocommerce',
		icon: 'calendar',
		supports: { html: false },
		attributes: {
			productId: { type: 'number', default: 0 },
			showTitle: { type: 'boolean', default: true },
			showRating: { type: 'boolean', default: true },
			showPrice: { type: 'boolean', default: true },
			showExcerpt: { type: 'boolean', default: true },
			showMeta: { type: 'boolean', default: true },
			showSharing: { type: 'boolean', default: true },
			availabilityAutoselectMode: { type: 'string', default: 'default' },
			customerTimezonesMode: { type: 'string', default: 'default' }
		},
		edit( props ) {
			const { attributes, setAttributes } = props;
			const blockProps = useBlockProps ? useBlockProps( { className: 'wc-appointments-appointment-form-block-editor' } ) : {};

			const [ search, setSearch ] = useState( '' );
			const [ options, setOptions ] = useState( [] );
			const [ loading, setLoading ] = useState( false );

			const [ product, setProduct ] = useState( null );
			const [ productLoading, setProductLoading ] = useState( false );

			useEffect( () => {
				let active = true;
				if ( !search ) {
					setOptions( [] );
					return;
				}
				setLoading( true );
				apiFetch( { path: `/wc/v3/products?search=${encodeURIComponent( search )}&per_page=20&status=publish&_fields=id,name,images` } )
					.then( ( results ) => {
						if ( !active ) return;
						const opts = Array.isArray( results ) ? results.map( ( p ) => ( { label: p.name, value: p.id, images: p.images } ) ) : [];
						setOptions( opts );
					} )
					.catch( () => { if ( active ) setOptions( [] ); } )
					.finally( () => { if ( active ) setLoading( false ); } );
				return () => { active = false; };
			}, [search] );

			useEffect( () => {
				let active = true;
				if ( !attributes.productId ) {
					setProduct( null );
					return;
				}
				setProductLoading( true );
				// Fetch additional fields for inline preview (rating, price, excerpt)
				apiFetch( { path: `/wc/v3/products/${attributes.productId}?_fields=id,name,images,short_description,price,price_html,average_rating,rating_count,permalink,type,requires_confirmation,meta_data` } )
					.then( ( p ) => { if ( active ) setProduct( p || null ); } )
					.catch( () => { if ( active ) setProduct( null ); } )
					.finally( () => { if ( active ) setProductLoading( false ); } );
				return () => { active = false; };
			}, [attributes.productId] );

			// Helper to render calendar-like skeleton grid.
			const renderSkeleton = () => {
				const headerDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
				const header = wp.element.createElement( 'div', { className: 'wc-appointments-cal-header' },
					headerDays.map( ( _, i ) => (
						wp.element.createElement( 'div', {
							key: `h-${i}`,
							className: 'wc-appointments-skeleton wc-appointments-cal-header-day'
						} )
					) )
				);

				const cells = [];
				for ( let r = 0; 6 > r; r++ ) {
					for ( let c = 0; 7 > c; c++ ) {
						cells.push( wp.element.createElement( 'div', {
							key: `${r}-${c}`,
							className: 'wc-appointments-skeleton wc-appointments-cal-cell'
						} ) );
					}
				}
				const grid = wp.element.createElement( 'div', { className: 'wc-appointments-cal-grid' }, cells );

				return wp.element.createElement( 'div', {
					className: 'wc-appointments-calendar-skeleton',
					role: 'img',
					'aria-label': __( 'Calendar Preview', 'woocommerce-appointments' )
				}, header, grid );
			};

			// Helper to compute button text using product.requires_confirmation when available.
			const getButtonText = ( p ) => {
				const hasRC = ( p && p.requires_confirmation !== undefined );
				const valRC = hasRC ? p.requires_confirmation : undefined;
				const md = Array.isArray( p && p.meta_data ) ? p.meta_data : [];
				const rcMd = md.find( ( m ) => m && ( '_requires_confirmation' === m.key || 'requires_confirmation' === m.key ) );
				const valMd = rcMd ? rcMd.value : false;
				const val = hasRC ? valRC : valMd;
				const truthy = ( true === val || 'yes' === val || '1' === val || 1 === val );
				return truthy ? __( 'Check Availability', 'woocommerce-appointments' ) : __( 'Book Now', 'woocommerce-appointments' );
			};

			return wp.element.createElement(
				'div',
				blockProps,
				// Block editor toolbar with Replace, Edit, and View actions
				// These mirror the in-block action buttons but live in the editor toolbar for quick access
				wp.element.createElement( BlockControls, {},
					wp.element.createElement( ToolbarGroup, {},
						// Replace product: clears the current selection to choose another product
						wp.element.createElement( ToolbarButton, {
							icon: 'update',
							label: __( 'Replace product', 'woocommerce-appointments' ),
							disabled: !( 0 < attributes.productId ),
							onClick: () => {
								// Reset selection and related search state
								setAttributes( { productId: 0 } );
								setSearch( '' );
								setOptions( [] );
							}
						} ),
						// Edit product: opens the admin edit screen for the selected product in a new tab
						wp.element.createElement( ToolbarButton, {
							icon: 'edit',
							label: __( 'Edit product', 'woocommerce-appointments' ),
							disabled: !( product && product.id ),
							onClick: () => {
								if ( product && product.id ) {
								// Use ajaxurl to derive correct admin path (works in multisite and single site).
									const adminPostUrl = ( window.ajaxurl || '/wp-admin/admin-ajax.php' ).replace( 'admin-ajax.php', 'post.php' );
									window.open( `${adminPostUrl}?post=${product.id}&action=edit`, '_blank' );
								}
							}
						} ),
						// View product: opens the product permalink in a new tab
						wp.element.createElement( ToolbarButton, {
							icon: 'external',
							label: __( 'View product', 'woocommerce-appointments' ),
							disabled: !( product && product.permalink ),
							onClick: () => {
								if ( product && product.permalink ) {
									window.open( product.permalink, '_blank' );
								}
							}
						} )
					)
				),
				// Sidebar controls: display and behavior only.
				wp.element.createElement( InspectorControls, {},
					wp.element.createElement( PanelBody, { title: __( 'Display Options', 'woocommerce-appointments' ), initialOpen: true },
						wp.element.createElement( ToggleControl, {
							label: __( 'Show Title', 'woocommerce-appointments' ),
							checked: !!attributes.showTitle,
							onChange: ( value ) => setAttributes( { showTitle: !!value } )
						} ),
						wp.element.createElement( ToggleControl, {
							label: __( 'Show Rating', 'woocommerce-appointments' ),
							checked: !!attributes.showRating,
							onChange: ( value ) => setAttributes( { showRating: !!value } )
						} ),
						wp.element.createElement( ToggleControl, {
							label: __( 'Show Price', 'woocommerce-appointments' ),
							checked: !!attributes.showPrice,
							onChange: ( value ) => setAttributes( { showPrice: !!value } )
						} ),
						wp.element.createElement( ToggleControl, {
							label: __( 'Show Excerpt', 'woocommerce-appointments' ),
							checked: !!attributes.showExcerpt,
							onChange: ( value ) => setAttributes( { showExcerpt: !!value } )
						} ),
						wp.element.createElement( ToggleControl, {
							label: __( 'Show Meta', 'woocommerce-appointments' ),
							checked: !!attributes.showMeta,
							onChange: ( value ) => setAttributes( { showMeta: !!value } )
						} ),
						wp.element.createElement( ToggleControl, {
							label: __( 'Show Sharing', 'woocommerce-appointments' ),
							checked: !!attributes.showSharing,
							onChange: ( value ) => setAttributes( { showSharing: !!value } )
						} )
					),
					wp.element.createElement( PanelBody, { title: __( 'Behavior', 'woocommerce-appointments' ), initialOpen: false },
						wp.element.createElement( SelectControl, {
							label: __( 'Auto-select Availability', 'woocommerce-appointments' ),
							value: attributes.availabilityAutoselectMode,
							options: [
								{ label: __( 'Default', 'woocommerce-appointments' ), value: 'default' },
								{ label: __( 'Enable', 'woocommerce-appointments' ), value: 'enable' },
								{ label: __( 'Disable', 'woocommerce-appointments' ), value: 'disable' }
							],
							onChange: ( value ) => setAttributes( { availabilityAutoselectMode: value } )
						} ),
						wp.element.createElement( SelectControl, {
							label: __( 'Customer Timezones', 'woocommerce-appointments' ),
							value: attributes.customerTimezonesMode,
							options: [
								{ label: __( 'Default', 'woocommerce-appointments' ), value: 'default' },
								{ label: __( 'Enable', 'woocommerce-appointments' ), value: 'enable' },
								{ label: __( 'Disable', 'woocommerce-appointments' ), value: 'disable' }
							],
							onChange: ( value ) => setAttributes( { customerTimezonesMode: value } )
						} )
					)
				),
				// In-block product selection UI.
				( !attributes.productId )
					? wp.element.createElement( Placeholder, {
						label: __( 'Appointment Form', 'woocommerce-appointments' )
					},
					wp.element.createElement( SearchControl, {
						label: __( 'Search Products', 'woocommerce-appointments' ),
						placeholder: __( 'Start typing to search.', 'woocommerce-appointments' ),
						value: search,
						onChange: ( value ) => setSearch( value )
					} ),
					loading
						? wp.element.createElement( Spinner, null )
						: ( search
							? ( options.length
								? wp.element.createElement( 'div', { className: 'wc-appointments-appointment-form-block-results' },
									options.map( ( opt ) =>
										wp.element.createElement( Button, {
											key: opt.value,
											isSecondary: true,
											onClick: () => setAttributes( { productId: opt.value } )
										}, opt.label )
									)
								)
								: wp.element.createElement( 'p', null, __( 'No results found.', 'woocommerce-appointments' ) ) )
							: null
						)
					)
					: wp.element.createElement( 'div', { className: 'wc-appointments-appointment-form-selected' },
						productLoading
							? wp.element.createElement( Spinner, null )
							: ( product
								? wp.element.createElement( 'div', { className: 'wc-appointments-appointment-form-selected-card' },
									// Removed product image to match Woo Product block editor UI
									wp.element.createElement( 'div', { className: 'wc-appointments-appointment-form-selected-details' },
										attributes.showTitle ? ( product && product.name ? wp.element.createElement( 'h2', { className: 'wc-appointments-preview-title' }, product.name ) : wp.element.createElement( 'div', { className: 'wc-appointments-skeleton wc-appointments-title-skeleton', style: { width: '60%', height: '24px' } } ) ) : null,
										attributes.showRating ? (
											( product && product.rating_count && 0 < parseFloat( product.average_rating || 0 ) )
												? wp.element.createElement( 'div', { className: 'wc-appointments-preview-rating' },
													wp.element.createElement( 'div', {
														className: 'star-rating',
														role: 'img',
														'aria-label': __( 'Rating', 'woocommerce-appointments' )
													},
													wp.element.createElement( 'span', {
														style: { width: `${Math.min( 5, Math.max( 0, parseFloat( product.average_rating || 0 ) ) ) / 5 * 100}%` }
													} )
													),
													wp.element.createElement( 'span', { className: 'rating-count' }, `(${product.rating_count || 0})` )
												)
												: wp.element.createElement( 'div', { className: 'wc-appointments-skeleton wc-appointments-rating-skeleton', style: { width: '120px', height: '16px' } } )
										) : null,
										attributes.showPrice ? ( product && product.price_html ? wp.element.createElement( 'div', { className: 'wc-appointments-preview-price', dangerouslySetInnerHTML: { __html: product.price_html } } ) : wp.element.createElement( 'div', { className: 'wc-appointments-skeleton wc-appointments-price-skeleton', style: { width: '80px', height: '20px' } } ) ) : null,
										attributes.showExcerpt ? ( product && product.short_description ? wp.element.createElement( 'div', { className: 'wc-appointments-preview-excerpt', dangerouslySetInnerHTML: { __html: product.short_description } } ) : wp.element.createElement( 'div', { className: 'wc-appointments-skeleton wc-appointments-excerpt-skeleton', style: { width: '100%', height: '40px' } } ) ) : null
									)
									// Inline action buttons removed in favor of editor toolbar controls
								)
								: wp.element.createElement( 'p', null, __( 'Selected product not found.', 'woocommerce-appointments' ) )
							),
						// Calendar-like skeleton preview of date picker
						renderSkeleton(),
						// Add-to-cart preview (below calendar), mimicking Woo Product block layout
						wp.element.createElement( 'div', { className: 'wc-appointments-add-to-cart-preview' },
							wp.element.createElement( 'div', { className: 'wc-appointments-quantity' },
								wp.element.createElement( 'label', { htmlFor: 'wc-appointments-quantity-input' }, '' ),
								wp.element.createElement( 'input', {
									type: 'number',
									id: 'wc-appointments-quantity-input',
									className: 'wc-appointments-quantity-input',
									min: 1,
									value: 1,
									readOnly: true
								} )
							),
							wp.element.createElement( Button, {
								isPrimary: true,
								disabled: true
							}, getButtonText( product ) )
						),
						attributes.showMeta ? ( product && product.id ? wp.element.createElement( 'div', { className: 'wc-appointments-preview-meta' }, __( 'Product ID', 'woocommerce-appointments' ) + ': ' + product.id ) : wp.element.createElement( 'div', { className: 'wc-appointments-skeleton wc-appointments-meta-skeleton', style: { width: '120px', height: '16px' } } ) ) : null,
						attributes.showSharing ? wp.element.createElement( 'div', { className: 'wc-appointments-preview-sharing' },
							wp.element.createElement( 'span', { className: 'wc-appointments-sharing-label' }, __( 'Share', 'woocommerce-appointments' ) ),
							wp.element.createElement( 'span', { className: 'wc-appointments-sharing-dot' } ),
							wp.element.createElement( 'span', { className: 'wc-appointments-sharing-dot' } ),
							wp.element.createElement( 'span', { className: 'wc-appointments-sharing-dot' } )
						) : null
					)
			);
		},
		save() { return null; }
	} );
} )();
