import React, { useContext, useEffect, useState } from 'react'
import { Modal, ModalBody, ModalHeader } from 'reactstrap-wc'
import { ButtonAria, Icon } from '$core-components'
import { t } from '$themelocalization'
import { RootDocumentContext } from '$themeservices'
import './AddressModal.scss'
import Popper from '../products/static/Popper'


const AddressModal = ({
	open,
	title = '',
	actionButtonText,
	cancelButtonText,
	onAction,
	onCancel,
	isActionDisabled = false,
	hasValidationErrors = false,
	onResetValidationError,
	children,
	className = '',
}) => {
	const { rootElement } = useContext(RootDocumentContext)()
	const bottomPriceRef = React.useRef(null)
	const topPriceRef = React.useRef(null)
	const stickPriceRef = React.useRef(null)


	const handleAction = () => {
		if (onAction) {
			onAction()
		}
	}

	const handleCancel = () => {
		if (onCancel) {
			onCancel()
		}
	}

	return (
		<Modal
			isOpen={open}
			className={`address-modal ${className}`}
			backdropClassName='address-modal-backdrop'
			container={rootElement}
		>
			<ModalHeader className='address-modal-header'>
				<div className='address-modal-title'>{title}</div>
				<button
					className='button button-transparent close-btn'
					onClick={handleCancel}
					aria-label={t('General.Close')}
				>
					<Icon name='close_black.svg' width='14px' height='14px' ariaHidden="true" />
				</button>
			</ModalHeader>

			<ModalBody className='address-modal-body'>
				<div>{children}</div>
				<div className='address-modal-actions'>
					{cancelButtonText && (
						<ButtonAria
							className='button button-secondary'
							onClick={handleCancel}
							text={cancelButtonText}
							noTruncate={true}
						/>
					)}
					{actionButtonText && (
						<ButtonAria
							className='button button-primary'
							onClick={handleAction}
							ref={bottomPriceRef}
							text={actionButtonText}
							disabled={isActionDisabled}
							noTruncate={true}
						/>
					)}
				</div>
			</ModalBody>
			<Popper
				bottomPriceRef={bottomPriceRef}
				topPriceRef={topPriceRef}
				stickPriceRef={stickPriceRef}
				errorCode={hasValidationErrors ? 'VALIDATION_ERROR' : null}
				forceAddToCartButton={true}
				resetError={onResetValidationError || (() => {})}
				popperAffectedSections={[]}
				isModal={true}
			/>
		</Modal>
	)
}

export default AddressModal
