import React, {useContext, useRef} from 'react'
import {createPortal} from 'react-dom'
import {t} from '$themelocalization'
import {useClickOutside} from '$themehooks'
import {RootDocumentContext} from '$themeservices'
import './PreflightWarningTooltip.scss'

const PreflightWarningTooltip = ({visible, onConfirm, onCancel, stickyPriceRef}) => {
  const {rootElement} = useContext(RootDocumentContext)()
  const tooltipRef = useRef(null)

  useClickOutside(tooltipRef, onCancel, rootElement)

  if (!visible) return null

  const warning = (window.UStoreProvider?.state?.customState?.get('preflightWarning') || '').replace(/\\"/g, '"')
  const hrefMatch = warning.match(/href="([^"]*)"/)
  const rawUrl = hrefMatch ? hrefMatch[1] : '#'
  const reportUrl = rawUrl === '#' || rawUrl.startsWith('http://') || rawUrl.startsWith('https://') || rawUrl.startsWith('/') ? rawUrl : '#'
  const reportLink = `<a href="${reportUrl}" target="_blank" rel="noopener noreferrer">${t('Preflight.WarningConfirmDownloadReport')}</a>`
  const message = `${t('Preflight.WarningConfirmMessageBefore')} ${reportLink} ${t('Preflight.WarningConfirmMessageAfter')}`

  const tooltipContent = (
    <div className="preflight-warning-content">
      <div className="preflight-warning-message" dangerouslySetInnerHTML={{__html: message}}/>
      <div className="preflight-warning-buttons">
        <button className="preflight-warning-cancel" onClick={onCancel} aria-label={t('Preflight.WarningConfirmCancel')}>{t('Preflight.WarningConfirmCancel')}</button>
        <button className="preflight-warning-next" onClick={onConfirm} aria-label={t('Preflight.WarningConfirmNext')}>{t('Preflight.WarningConfirmNext')}</button>
      </div>
    </div>
  )

  const stickyPanel = stickyPriceRef?.current?.closest('.product-sticky-price')
  const stickyButtonContainer = stickyPriceRef?.current?.closest('.sticky-add-to-cart-icon-container')
  const isStickyVisible = stickyPanel && stickyPanel.offsetHeight > 0
  const isMobile = typeof window !== 'undefined' && window.innerWidth <= 767

  if (isStickyVisible) {
    if (isMobile && stickyPanel) {
      return createPortal(
        <div ref={tooltipRef} className="preflight-warning-tooltip sticky-mode">
          {tooltipContent}
          <span className="preflight-warning-arrow"/>
        </div>,
        stickyPanel
      )
    }
    if (!isMobile && stickyButtonContainer) {
      stickyButtonContainer.style.position = 'relative'
      return createPortal(
        <div ref={tooltipRef} className="preflight-warning-tooltip sticky-mode sticky-desktop">
          {tooltipContent}
          <span className="preflight-warning-arrow"/>
        </div>,
        stickyButtonContainer
      )
    }
  }

  return (
    <div ref={tooltipRef} className="preflight-warning-tooltip">
      {tooltipContent}
      <span className="preflight-warning-arrow"/>
    </div>
  )
}

export default PreflightWarningTooltip
