import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import RtgwModal from './Modal';
import { themeVars } from '../color';

/** Inline gift icon — replaces the emoji so the toggle reads as a deliberate
 *  line-icon set, consistent with the rest of the RT plugin family. */
function GiftIcon() {
	return (
		<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true">
			<path fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" d="M4 9.5h16v3H4zM5.5 12.5h13V20a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1z" />
			<path fill="none" stroke="currentColor" strokeWidth="1.8" d="M12 9.5V21" />
			<path fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" d="M12 9.5c-1.4 0-4-.6-4-2.8A2.2 2.2 0 0 1 10.2 4.5C12 4.5 12 7.5 12 9.5zM12 9.5c1.4 0 4-.6 4-2.8a2.2 2.2 0 0 0-2.2-2.2C12 4.5 12 7.5 12 9.5z" />
		</svg>
	);
}

/** Small elegant checkmark used on the "Update" action. */
function CheckIcon() {
	return (
		<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
			<path fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" d="M20 6 9 17l-5-5" />
		</svg>
	);
}

/** Trash icon used on the quick-remove control beside the toggle. */
function TrashIcon() {
	return (
		<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
			<path fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" d="M5 7h14M9.5 7V5a1.5 1.5 0 0 1 1.5-1.5h2A1.5 1.5 0 0 1 14.5 5v2M7 7l.8 12.1A2 2 0 0 0 9.8 21h4.4a2 2 0 0 0 2-1.9L17 7" />
		</svg>
	);
}

/** Action rendered as an <a role="button"> so every clickable control in the
 *  gift wrap UI (toggle, remove, add/update) shares one semantic and one
 *  visual language instead of mixing native buttons and links. */
function ActionLink( { variant = 'primary', disabled = false, onClick, children } ) {
	return (
		<a
			href="#rtgw-gift-wrap"
			role="button"
			aria-disabled={ disabled ? 'true' : undefined }
			className={ `rtgw-action rtgw-action--${ variant }${ disabled ? ' is-disabled' : '' }` }
			onClick={ ( e ) => {
				e.preventDefault();
				if ( ! disabled ) {
					onClick( e );
				}
			} }
		>
			{ children }
		</a>
	);
}

/**
 * The style grid + optional message textarea — the part of the UI a
 * shopper actually chooses from. Shared between the popup layout's modal
 * and the grid layout's inline panel so both stay visually identical.
 */
function StylePicker( { wrapOptions, hasChoice, settings, draftStyleIndex, setDraftStyleIndex, draftMessage, setDraftMessage, radioName, gridStyle = false } ) {
	return (
		<>
			{ hasChoice && (
				<div className={ gridStyle ? 'rtgw-style-grid' : 'rtgw-style-options' }>
					{ wrapOptions.map( ( option, index ) => {
						const isSelected = String( index ) === String( draftStyleIndex );

						return (
							<label
								key={ index }
								className={ `${ gridStyle ? 'rtgw-style-grid-option' : 'rtgw-style-option' }${ isSelected ? ' is-selected' : '' }` }
							>
								<input
									type="radio"
									name={ radioName }
									checked={ isSelected }
									onChange={ () => setDraftStyleIndex( String( index ) ) }
								/>
								{ option.image_url ? (
									<img className={ gridStyle ? 'rtgw-style-grid-option__thumb' : 'rtgw-style-option__thumb' } src={ option.image_url } alt="" />
								) : (
									<span className={ `${ gridStyle ? 'rtgw-style-grid-option__thumb' : 'rtgw-style-option__thumb' } ${ gridStyle ? 'rtgw-style-grid-option__thumb--placeholder' : 'rtgw-style-option__thumb--placeholder' }` }><GiftIcon /></span>
								) }
								<span className={ gridStyle ? 'rtgw-style-grid-option__text' : 'rtgw-style-option__text' }>
									{ option.name }
									{ option.price_text ? ` (${ option.price_text })` : '' }
								</span>
							</label>
						);
					} ) }
				</div>
			) }

			{ settings.allow_message && (
				<textarea
					className="rtgw-message-input"
					placeholder={ settings.message_label || __( 'Gift message (optional)', 'rt-gift-wrap-for-woocommerce' ) }
					value={ draftMessage }
					maxLength={ settings.message_max_length || 200 }
					rows={ 3 }
					onChange={ ( e ) => setDraftMessage( e.target.value ) }
				/>
			) }
		</>
	);
}

/**
 * The gift wrap UI itself. Two layouts, chosen via `layout`:
 *  - 'popup' — a toggle button that opens an elegant modal for picking a
 *    style and adding a message.
 *  - 'grid' — the style grid and message field sit directly inline in the
 *    checkout, no popup at all; a quick-remove icon still handles removal.
 * Used identically by both checkout types (src/checkout-classic/GiftWrapBox.jsx
 * and src/checkout-block/GiftWrapBlock.jsx) so the markup, classnames, and
 * styling (see gift-wrap-fields.scss) are the same regardless of which
 * checkout the shopper is on — only how the selection gets saved differs
 * (hidden form fields + jQuery `update_checkout` for classic,
 * `extensionCartUpdate()` via the Store API for the block).
 *
 * Both layouts edit a local draft and only call back once, on confirm/remove
 * — callers get one atomic `{ styleIndex, message }` payload rather than
 * three separate setter calls, so there's exactly one persistence call per
 * user action instead of several rapid, possibly-stale ones.
 */
export default function GiftWrapFields( {
	settings,
	layout = 'popup',
	isOpen,
	styleIndex,
	message,
	onConfirm, // ({ styleIndex, message }) => void — gift wrap added/updated
	onRemove, // () => void — gift wrap removed
	busy = false,
} ) {
	const [ isModalOpen, setIsModalOpen ] = useState( false );
	const [ draftStyleIndex, setDraftStyleIndex ] = useState( styleIndex );
	const [ draftMessage, setDraftMessage ] = useState( message );

	if ( ! settings || ! settings.enabled ) {
		return null;
	}

	const wrapOptions = settings.wrap_options || [];
	const hasChoice = wrapOptions.length > 1;
	const isGrid = layout === 'grid';

	const openModal = () => {
		setDraftStyleIndex( styleIndex );
		setDraftMessage( message );
		setIsModalOpen( true );
	};

	const closeModal = () => setIsModalOpen( false );

	const confirmAdd = () => {
		onConfirm( { styleIndex: draftStyleIndex, message: draftMessage } );
		closeModal();
	};

	const selectedOption = wrapOptions[ parseInt( styleIndex, 10 ) ] || wrapOptions[ 0 ];
	const accentStyle = themeVars( settings.theme_color );

	// Quick remove — lets a shopper drop the gift wrap in one tap without
	// opening the modal (or, on the grid layout, without any popup at all).
	const quickRemove = ( e ) => {
		e.preventDefault();
		if ( ! busy ) {
			onRemove();
		}
	};

	if ( isGrid ) {
		return (
			<div className={ `rtgw-gift-wrap-block rtgw-layout-grid${ isOpen ? ' is-open' : '' }` } style={ accentStyle }>
				<div className="rtgw-grid-panel">
					<div className="rtgw-grid-panel__head">
						<span className="rtgw-grid-panel__icon"><GiftIcon /></span>
						<span className="rtgw-grid-panel__label">
							{ settings.label || __( 'Gift Wrap', 'rt-gift-wrap-for-woocommerce' ) }
						</span>
						{ isOpen && (
							<a
								href="#rtgw-remove-gift-wrap"
								role="button"
								className={ `rtgw-quick-remove${ busy ? ' is-disabled' : '' }` }
								aria-disabled={ busy ? 'true' : undefined }
								aria-label={ __( 'Remove gift wrap', 'rt-gift-wrap-for-woocommerce' ) }
								title={ __( 'Remove gift wrap', 'rt-gift-wrap-for-woocommerce' ) }
								onClick={ quickRemove }
							>
								<TrashIcon />
							</a>
						) }
					</div>

					<StylePicker
						wrapOptions={ wrapOptions }
						hasChoice={ hasChoice }
						settings={ settings }
						draftStyleIndex={ draftStyleIndex }
						setDraftStyleIndex={ setDraftStyleIndex }
						draftMessage={ draftMessage }
						setDraftMessage={ setDraftMessage }
						radioName="rtgw-style-grid"
						gridStyle
					/>

					<ActionLink variant="primary" onClick={ confirmAdd } disabled={ busy }>
						{ isOpen && <CheckIcon /> }
						{ isOpen
							? __( 'Update', 'rt-gift-wrap-for-woocommerce' )
							: __( 'Add to order', 'rt-gift-wrap-for-woocommerce' ) }
					</ActionLink>
				</div>
			</div>
		);
	}

	return (
		<div className={ `rtgw-gift-wrap-block rtgw-layout-${ layout }${ isOpen ? ' is-open' : '' }` } style={ accentStyle }>
			<div className="rtgw-toggle-row">
				<a
					href="#rtgw-gift-wrap"
					role="button"
					className={ `rtgw-toggle-button${ isOpen ? ' is-open' : '' }${ busy ? ' is-disabled' : '' }` }
					aria-disabled={ busy ? 'true' : undefined }
					onClick={ ( e ) => {
						e.preventDefault();
						if ( ! busy ) {
							openModal();
						}
					} }
				>
					<span className="rtgw-toggle-button__icon"><GiftIcon /></span>
					<span className="rtgw-toggle-button__label">
						{ isOpen
							? ( selectedOption
								? `${ settings.label || __( 'Gift Wrap', 'rt-gift-wrap-for-woocommerce' ) } — ${ selectedOption.name }`
								: settings.label || __( 'Gift Wrap', 'rt-gift-wrap-for-woocommerce' ) )
							: settings.label || __( 'Add Gift Wrap', 'rt-gift-wrap-for-woocommerce' ) }
					</span>
					{ isOpen && <span className="rtgw-toggle-button__badge">{ __( 'Added', 'rt-gift-wrap-for-woocommerce' ) }</span> }
				</a>

				{ isOpen && (
					<a
						href="#rtgw-remove-gift-wrap"
						role="button"
						className={ `rtgw-quick-remove${ busy ? ' is-disabled' : '' }` }
						aria-disabled={ busy ? 'true' : undefined }
						aria-label={ __( 'Remove gift wrap', 'rt-gift-wrap-for-woocommerce' ) }
						title={ __( 'Remove gift wrap', 'rt-gift-wrap-for-woocommerce' ) }
						onClick={ quickRemove }
					>
						<TrashIcon />
					</a>
				) }
			</div>

			{ isModalOpen && (
				<RtgwModal
					title={ settings.label || __( 'Gift Wrap', 'rt-gift-wrap-for-woocommerce' ) }
					onRequestClose={ closeModal }
					className="rtgw-modal"
					style={ accentStyle }
				>
					<p className="rtgw-modal__intro">
						{ __( 'Choose a style below for a beautifully wrapped presentation.', 'rt-gift-wrap-for-woocommerce' ) }
					</p>

					<StylePicker
						wrapOptions={ wrapOptions }
						hasChoice={ hasChoice }
						settings={ settings }
						draftStyleIndex={ draftStyleIndex }
						setDraftStyleIndex={ setDraftStyleIndex }
						draftMessage={ draftMessage }
						setDraftMessage={ setDraftMessage }
						radioName="rtgw-style-modal"
					/>

					<div className="rtgw-modal__footer">
						<ActionLink variant="primary" onClick={ confirmAdd } disabled={ busy }>
							{ isOpen && <CheckIcon /> }
							{ isOpen
								? __( 'Update', 'rt-gift-wrap-for-woocommerce' )
								: __( 'Add to order', 'rt-gift-wrap-for-woocommerce' ) }
						</ActionLink>
					</div>
				</RtgwModal>
			) }
		</div>
	);
}
