import { useState } from '@wordpress/element';
import { extensionCartUpdate } from '@woocommerce/blocks-checkout';
import GiftWrapFields from '../shared/components/GiftWrapFields';

/**
 * Checkout-block wiring around the shared GiftWrapFields UI: owns state
 * and pushes changes to the server via extensionCartUpdate() (handled in
 * PHP by includes/class-rtgw-store-api-extend.php), in one atomic call per
 * user action (add/update or remove). This block has no attributes of its
 * own — appearance (label, theme colour, layout) is read entirely from the
 * plugin's global settings, same as the classic checkout, so both render
 * from one source of truth instead of a per-block override.
 *
 * Receives `extensions` automatically — populated from our Store API
 * ExtendSchema registration — carrying the current session's gift wrap
 * selection so state survives page reloads/navigation within checkout.
 */
export default function GiftWrapBlock( { extensions = {} } ) {
	const rtgwData = extensions.rtgw || {};
	const settings = window.rtgwCheckoutData?.settings || {};
	const layout = settings.layout || 'popup';

	const [ isOpen, setIsOpen ] = useState( !! rtgwData.wants_gift_wrap );
	const [ styleIndex, setStyleIndex ] = useState( rtgwData.style_index || '0' );
	const [ message, setMessage ] = useState( rtgwData.message || '' );
	const [ busy, setBusy ] = useState( false );

	const push = ( payload ) => {
		setBusy( true );
		const result = extensionCartUpdate( { namespace: 'rtgw', data: payload } );

		if ( result && typeof result.finally === 'function' ) {
			result.finally( () => setBusy( false ) );
		} else {
			setBusy( false );
		}
	};

	return (
		<GiftWrapFields
			settings={ settings }
			layout={ layout }
			isOpen={ isOpen }
			styleIndex={ styleIndex }
			message={ message }
			busy={ busy }
			onConfirm={ ( { styleIndex: nextStyle, message: nextMessage } ) => {
				setIsOpen( true );
				setStyleIndex( nextStyle );
				setMessage( nextMessage );
				push( { wants_gift_wrap: true, style_index: nextStyle, message: nextMessage } );
			} }
			onRemove={ () => {
				setIsOpen( false );
				push( { wants_gift_wrap: false, style_index: styleIndex, message } );
			} }
		/>
	);
}
