import { TextField } from '../../shared/components/Fields';
import Button from '../../shared/components/Button';
import MediaPicker from '../../shared/components/MediaPicker';
import { __ } from '@wordpress/i18n';

export default function WrapOptionsPanel( { options, onChange } ) {
	const updateOption = ( index, field, value ) => {
		const next = options.map( ( option, i ) =>
			i === index ? { ...option, [ field ]: value } : option
		);
		onChange( next );
	};

	const updateOptionFields = ( index, fields ) => {
		const next = options.map( ( option, i ) =>
			i === index ? { ...option, ...fields } : option
		);
		onChange( next );
	};

	const removeOption = ( index ) => {
		onChange( options.filter( ( _, i ) => i !== index ) );
	};

	const addOption = () => {
		onChange( [ ...options, { name: '', price: 0, image_id: 0, image_url: '' } ] );
	};

	return (
		<div className="rtgw-wrap-options">
			<p className="rtgw-wrap-options__help">
				{ __( 'Add one or more wrap styles with their own price and preview image. If you add more than one, customers pick a style at checkout.', 'rt-gift-wrap-for-woocommerce' ) }
			</p>

			{ options.map( ( option, index ) => (
				<div className="rtgw-wrap-option-card" key={ index }>
					<MediaPicker
						imageId={ option.image_id }
						imageUrl={ option.image_url }
						onSelect={ ( id, url ) =>
							updateOptionFields( index, { image_id: id, image_url: url } )
						}
						onRemove={ () =>
							updateOptionFields( index, { image_id: 0, image_url: '' } )
						}
					/>

					<div className="rtgw-wrap-option-card__fields">
						<TextField
							label={ __( 'Style Name', 'rt-gift-wrap-for-woocommerce' ) }
							value={ option.name }
							onChange={ ( value ) => updateOption( index, 'name', value ) }
						/>
						<TextField
							type="number"
							step="0.01"
							min="0"
							label={ __( 'Price', 'rt-gift-wrap-for-woocommerce' ) }
							value={ option.price }
							onChange={ ( value ) => updateOption( index, 'price', parseFloat( value ) || 0 ) }
						/>
					</div>

					<Button
						variant="ghost"
						size="sm"
						onClick={ () => removeOption( index ) }
						disabled={ options.length <= 1 }
					>
						{ __( 'Remove', 'rt-gift-wrap-for-woocommerce' ) }
					</Button>
				</div>
			) ) }

			<Button variant="secondary" onClick={ addOption }>
				+ { __( 'Add Style', 'rt-gift-wrap-for-woocommerce' ) }
			</Button>
		</div>
	);
}
