/**
 * External dependencies
 */
import { __, sprintf } from '@wordpress/i18n';
import { DISPLAY_CART_PRICES_INCLUDING_TAX } from '@kkart/block-settings';
import LoadingMask from '@kkart/base-components/loading-mask';
import { RemovableChip } from '@kkart/base-components/chip';
import PropTypes from 'prop-types';

/**
 * Internal dependencies
 */
import TotalsItem from '../totals-item';
import './style.scss';

const TotalsDiscountItem = ( {
	cartCoupons = [],
	currency,
	isRemovingCoupon,
	removeCoupon,
	values,
} ) => {
	const {
		total_discount: totalDiscount,
		total_discount_tax: totalDiscountTax,
	} = values;
	const discountValue = parseInt( totalDiscount, 10 );

	if ( ! discountValue && cartCoupons.length === 0 ) {
		return null;
	}

	const discountTaxValue = parseInt( totalDiscountTax, 10 );
	const discountTotalValue = DISPLAY_CART_PRICES_INCLUDING_TAX
		? discountValue + discountTaxValue
		: discountValue;

	return (
		<TotalsItem
			className="kkart-block-components-totals-discount"
			currency={ currency }
			description={
				cartCoupons.length !== 0 && (
					<LoadingMask
						screenReaderLabel={ __(
							'Removing coupon…',
							'kkart'
						) }
						isLoading={ isRemovingCoupon }
						showSpinner={ false }
					>
						<ul className="kkart-block-components-totals-discount__coupon-list">
							{ cartCoupons.map( ( cartCoupon ) => (
								<RemovableChip
									key={ 'coupon-' + cartCoupon.code }
									className="kkart-block-components-totals-discount__coupon-list-item"
									text={ cartCoupon.code }
									screenReaderText={ sprintf(
										/* Translators: %s Coupon code. */
										__(
											'Coupon: %s',
											'kkart'
										),
										cartCoupon.code
									) }
									disabled={ isRemovingCoupon }
									onRemove={ () => {
										removeCoupon( cartCoupon.code );
									} }
									radius="large"
									ariaLabel={ sprintf(
										/* Translators: %s is a coupon code. */
										__(
											'Remove coupon "%s"',
											'kkart'
										),
										cartCoupon.code
									) }
								/>
							) ) }
						</ul>
					</LoadingMask>
				)
			}
			label={
				!! discountTotalValue
					? __( 'Discount', 'kkart' )
					: __( 'Coupons', 'kkart' )
			}
			value={ discountTotalValue ? discountTotalValue * -1 : '-' }
		/>
	);
};

TotalsDiscountItem.propTypes = {
	cartCoupons: PropTypes.arrayOf(
		PropTypes.shape( {
			code: PropTypes.string.isRequired,
		} )
	),
	currency: PropTypes.object.isRequired,
	isRemovingCoupon: PropTypes.bool.isRequired,
	removeCoupon: PropTypes.func.isRequired,
	values: PropTypes.shape( {
		total_discount: PropTypes.string,
		total_discount_tax: PropTypes.string,
	} ).isRequired,
};

export default TotalsDiscountItem;
