/**
 * External dependencies
 */
import { __ } from '@wordpress/i18n';
import FormattedMonetaryAmount from '@kkart/base-components/formatted-monetary-amount';
import { decodeEntities } from '@wordpress/html-entities';
import { getCurrencyFromPriceResponse } from '@kkart/base-utils';
import { ShippingRatesControl } from '@kkart/base-components/cart-checkout';
import { DISPLAY_CART_PRICES_INCLUDING_TAX } from '@kkart/block-settings';

const renderShippingRatesControlOption = ( option ) => {
	const priceWithTaxes = DISPLAY_CART_PRICES_INCLUDING_TAX
		? parseInt( option.price, 10 ) + parseInt( option.taxes, 10 )
		: parseInt( option.price, 10 );
	return {
		label: decodeEntities( option.name ),
		value: option.rate_id,
		description: (
			<>
				{ Number.isFinite( priceWithTaxes ) && (
					<FormattedMonetaryAmount
						currency={ getCurrencyFromPriceResponse( option ) }
						value={ priceWithTaxes }
					/>
				) }
				{ Number.isFinite( priceWithTaxes ) && option.delivery_time
					? ' — '
					: null }
				{ decodeEntities( option.delivery_time ) }
			</>
		),
	};
};

const ShippingRateSelector = ( {
	hasRates,
	shippingRates,
	shippingRatesLoading,
} ) => {
	return (
		<fieldset className="kkart-block-components-totals-shipping__fieldset">
			<legend className="screen-reader-text">
				{ hasRates
					? __( 'Shipping options', 'kkart' )
					: __(
							'Choose a shipping option',
							'kkart'
					  ) }
			</legend>
			<ShippingRatesControl
				className="kkart-block-components-totals-shipping__options"
				collapsibleWhenMultiple={ true }
				noResultsMessage={ __(
					'No shipping options were found.',
					'kkart'
				) }
				renderOption={ renderShippingRatesControlOption }
				shippingRates={ shippingRates }
				shippingRatesLoading={ shippingRatesLoading }
			/>
		</fieldset>
	);
};

export default ShippingRateSelector;
