/**
 * External dependencies
 */
import { __ } from '@wordpress/i18n';
import { useState, useEffect, useRef } from '@wordpress/element';
import Button from '@kkart/base-components/button';
import { ValidatedTextInput } from '@kkart/base-components/text-input';
import Label from '@kkart/base-components/label';
import { ValidationInputError } from '@kkart/base-components/validation';
import LoadingMask from '@kkart/base-components/loading-mask';
import PropTypes from 'prop-types';
import { withInstanceId } from '@kkart/base-hocs/with-instance-id';
import { useValidationContext } from '@kkart/base-context';
import Panel from '@kkart/base-components/panel';

/**
 * Internal dependencies
 */
import './style.scss';

const TotalsCouponCodeInput = ( {
	instanceId,
	isLoading = false,
	initialOpen = false,
	onSubmit = () => {},
} ) => {
	const [ couponValue, setCouponValue ] = useState( '' );
	const currentIsLoading = useRef( false );
	const { getValidationError, getValidationErrorId } = useValidationContext();

	const validationError = getValidationError( 'coupon' );

	useEffect( () => {
		if ( currentIsLoading.current !== isLoading ) {
			if ( ! isLoading && couponValue && ! validationError ) {
				setCouponValue( '' );
			}
			currentIsLoading.current = isLoading;
		}
	}, [ isLoading, couponValue, validationError ] );

	const textInputId = `kkart-block-components-totals-coupon__input-${ instanceId }`;

	return (
		<Panel
			className="kkart-block-components-totals-coupon"
			hasBorder={ true }
			initialOpen={ initialOpen }
			title={
				<Label
					label={ __(
						'Coupon Code?',
						'kkart'
					) }
					screenReaderLabel={ __(
						'Introduce Coupon Code',
						'kkart'
					) }
					htmlFor={ textInputId }
				/>
			}
			titleTag="h2"
		>
			<LoadingMask
				screenReaderLabel={ __(
					'Applying coupon…',
					'kkart'
				) }
				isLoading={ isLoading }
				showSpinner={ false }
			>
				<div className="kkart-block-components-totals-coupon__content">
					<form className="kkart-block-components-totals-coupon__form">
						<ValidatedTextInput
							id={ textInputId }
							errorId="coupon"
							className="kkart-block-components-totals-coupon__input"
							label={ __(
								'Enter code',
								'kkart'
							) }
							value={ couponValue }
							ariaDescribedBy={ getValidationErrorId(
								textInputId
							) }
							onChange={ ( newCouponValue ) => {
								setCouponValue( newCouponValue );
							} }
							validateOnMount={ false }
							focusOnMount={ true }
							showError={ false }
						/>
						<Button
							className="kkart-block-components-totals-coupon__button"
							disabled={ isLoading || ! couponValue }
							showSpinner={ isLoading }
							onClick={ ( e ) => {
								e.preventDefault();
								onSubmit( couponValue );
							} }
							type="submit"
						>
							{ __( 'Apply', 'kkart' ) }
						</Button>
					</form>
					<ValidationInputError
						propertyName="coupon"
						elementId={ textInputId }
					/>
				</div>
			</LoadingMask>
		</Panel>
	);
};

TotalsCouponCodeInput.propTypes = {
	onSubmit: PropTypes.func,
	isLoading: PropTypes.bool,
};

export default withInstanceId( TotalsCouponCodeInput );
