import React, {useState, useContext, useEffect} from 'react'
import {Modal, ModalBody} from 'reactstrap-wc'
import {RootDocumentContext} from '$themeservices'
import {ImageZoom} from '$core-components'
import {t} from '$themelocalization'
import theme from '$styles/theme'
import './ProductApproval.scss'
import Preview from '../Preview'

const preloadImage = async src =>
  new Promise((resolve, reject) => {
    const image = new Image()
    image.onload = (e) => resolve(image)
    image.onerror = reject
    image.src = src
  })

const ProductApproval = ({
                           type,
                           isModalOpen,
                           onCloseModal,
                           src,
                           onAddToCartClick,
                           addToCartBtnText,
                           checkboxText,
                           errorText
                         }) => {
  const {rootElement} = useContext(RootDocumentContext)()
  const isMobile = document.body.clientWidth < parseInt(theme.lg.replace('px', ''))

  const [isProofPdf, setIsProofPdf] = useState(type === 'application/pdf')
  const [isimage, setIsimage] = useState(type && typeof type === 'string' && type.startsWith('image/'))
  const [approved, setApproved] = useState(false)
  const [showError, setShowError] = useState(false)

  useEffect(() => {
    (async () => {
      if (!src) {
        return
      }
      try {
        await preloadImage(src)
        setIsProofPdf(false)
        setIsimage(true)
      } catch (err) {
        setIsProofPdf(true)
        setIsimage(false)
      }
    })()
  }, [src])

  const onAddClicked = () => {
    if (approved) {
      setShowError(false)
      onAddToCartClick()
    } else {
      setShowError(true)
    }
  }

  if (!src) {
    return null
  }
  
  return (
    <Modal toggle={onCloseModal} isOpen={isModalOpen} modalClassName="proof-approval" container={rootElement}>
      <div className={`${isProofPdf ? 'transparent' : ''} modal-close`}>
        <div className='close-btn' role="button" tabIndex={0} onClick={onCloseModal} onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onCloseModal() } }} aria-label={t('General.Close')}>×</div>
      </div>
      <ModalBody>
        <div className={`approval-title mobile`}>
          {t('productProof.review_label')}
        </div>
        {isProofPdf && !isMobile &&
          <div className='approve-modal-pdf'>
            <object data={src + '&inline=true&#view=Fit'}
              type="application/pdf"
              width="100%"
              height="100%"
            >
              <div className='download-pdf-wrapper'>
                <a href={src}>{t('productProof.download')}</a>
              </div>
            </object>
          </div>
        }
        {isProofPdf && isMobile &&
          <div className={`approve-modal-pdf mobile`}>
            <div className='download-pdf-wrapper'>
              <a download href={src}>{t('productProof.download')}</a>
            </div>
          </div>
        }
        {isimage && (
          !isMobile
            ? <div className="approval-image-wrapper"><ImageZoom src={src} /></div>
            : <div className="approval-image-wrapper mobile">
                <div className="proof-modal-image mobile">
                  <Preview
                      productApprovalThumbnails={[{Url: src}]}
                  />
                </div>
              </div>
        )
        }
        <div className={`proof-approval ${isMobile ? 'mobile' : ''}`}>
          <div className="approval-title desktop">
            {t('productProof.review_label')}
          </div>
          <div className="approval-checkbox">
            <label>
              <input type="checkbox" aria-required="true" onChange={() => { setApproved(prev => !prev) }} />
              <span className='checkbox-label'>{checkboxText || t('productProof.ProofIsApproved')}</span>
              <span className="required">*</span>
            </label>
          </div>
          {
            showError && <div className='proof-approval-required' role="alert">
              <span>{errorText || t('productProof.ConfirmProof')}</span>
            </div>
          }
          <div
            className='button button-primary add-to-cart-button'
            role="button" tabIndex={0}
            onClick={onAddClicked}
            onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onAddClicked() } }}
          >
            {addToCartBtnText}
          </div>
        </div>
      </ModalBody>
    </Modal >
  )
}

export default ProductApproval
