import React, {useState, useContext, useId } from 'react'
import { createPortal } from 'react-dom'
import { observer } from 'mobx-react-lite'
import { UStoreProvider } from '@ustore/core'
import { RootDocumentContext } from '$themeservices'
import { useMobile } from '$themehooks'
import ItemDuplicateTooltip from './ItemDuplicateTooltip'
import DuplicateItemsDialogError from './DuplicateItemsDialogError'
import ConfirmDuplicationModal from './ConfirmDuplicationModal'
import DuplicateButton from './DuplicateButton.js'
import DuplicateCopiesPopup from './DuplicateCopiesPopup'
import { t } from '$themelocalization'

import './DuplicateAction.scss'
import CartErrorModel from '../model/CartErrorModel'

const STORE_TYPE_CONNECT_ENTERPRISE = 4

const getStoreAttr = (name) =>
  UStoreProvider.state.get().currentStore.Attributes.find(attr => attr.Name === name)?.Value


const DuplicateAction = ({ item, list, showLargeIcon = false }) => {
  const entity = item || list
  const {rootElement} = useContext(RootDocumentContext)()
  const isMobileView = useMobile('lg')
  const [duplicateTooltipMessage, setDuplicateTooltipMessage] = useState(null)
  const [duplicateDialogMessage, setDuplicateDialogMessage] = useState(null)
  const desktopDuplicateButtonRef = React.useRef(null)
  const [showDuplicateListModal, setShowDuplicateListModal] = useState(false)
  const [showCopiesPopup, setShowCopiesPopup] = useState(false)
  const tooltipId = useId()

  const isConnectEnterprise = UStoreProvider.state.get().currentStore.StoreType === STORE_TYPE_CONNECT_ENTERPRISE
  const showCopiesForDuplication = getStoreAttr('ShowCopiesForDuplication') === 'True'
  const duplicationMaxItems = parseInt(getStoreAttr('DuplicationMaxItems') || '0', 10)
  const shouldShowCopiesPopup = !!item && showCopiesForDuplication && !isConnectEnterprise

  const duplicate = async (isMobile, copies = 1) => {
    const res = await entity.duplicate(copies)
    if ([CartErrorModel.CART_ERROR_TYPES.ProductComponentNotAvailable, CartErrorModel.CART_ERROR_TYPES.ProductNotAvailable ].includes(res?.Type)) {
      if (isMobile) {
        setDuplicateDialogMessage(res.Message)
      } else {
        setDuplicateTooltipMessage(res.Message)
      }
    }
  }

  const onDuplicate = async (isMobile) => {
    if (list || (item?.isKit && (item?.hasUSAData || item?.isCOD || item?.hasItemsOffline))) {
      setShowDuplicateListModal(true)
      return
    }
    const kitExceedsLimit = item?.isKit && duplicationMaxItems > 0 && item.kitItemsCount > duplicationMaxItems
    if (shouldShowCopiesPopup && !kitExceedsLimit) {
      setShowCopiesPopup(true)
      return
    }
    await duplicate(isMobile)
  }

  const onCopiesDuplicate = (copies) => {
    setShowCopiesPopup(false)
    duplicate(isMobileView, copies)
  }

  const hoverHandler = () => {
    if (list?.eligibleItemsCount > list?.duplicationLimit ) {
      setDuplicateTooltipMessage(t("Cart.Duplicate.DuplicateRestriction", { count: list.duplicationLimit}))
    }
  }

  const clearTooltip = () => setDuplicateTooltipMessage(null)

  return <div className="cart-entity-duplicate-action-container">
    <DuplicateButton
      ref={desktopDuplicateButtonRef}
      className="action desktop-duplicate-button"
      onClick={() => onDuplicate(false)}
      hoverhandler={ list && hoverHandler}
      clearTooltip={clearTooltip}
      disabled={list?.eligibleItemsCount > list?.duplicationLimit || list?.itemsCount === 0}
      showLargeIcon={showLargeIcon}
      ariaDescribedBy={duplicateTooltipMessage ? tooltipId : undefined}
    />

    <DuplicateButton
      className="action mobile-duplicate-button"
      onClick={() => onDuplicate(true)}
      disabled={list?.itemsCount === 0}
      showLargeIcon={showLargeIcon}
    />

    {duplicateTooltipMessage &&
      createPortal(
        <ItemDuplicateTooltip id={tooltipId}
                              message={duplicateTooltipMessage}
                              isList={!!list}
                              desktopDuplicateButtonRef={desktopDuplicateButtonRef}
                              onClickOutside={() => setDuplicateTooltipMessage(null)}/>, rootElement)}
    {duplicateDialogMessage && <DuplicateItemsDialogError message={duplicateDialogMessage} onClose={() => setDuplicateDialogMessage(null)} />}
    {showDuplicateListModal &&
      <ConfirmDuplicationModal
        onClose={() => setShowDuplicateListModal(false)}
        onDuplicate={async (isMobile) => {
          setShowDuplicateListModal(false)
          await duplicate(isMobile)
        }}
        entity={entity}
      />
    }
    {showCopiesPopup && (isMobileView
      ? <DuplicateCopiesPopup
          onClose={() => setShowCopiesPopup(false)}
          onDuplicate={onCopiesDuplicate}
          duplicationMaxItems={duplicationMaxItems}
          kitItemsCount={item?.isKit ? item.kitItemsCount : 0}
          isMobile
        />
      : createPortal(
          <DuplicateCopiesPopup
            desktopDuplicateButtonRef={desktopDuplicateButtonRef}
            onClose={() => setShowCopiesPopup(false)}
            onDuplicate={onCopiesDuplicate}
            duplicationMaxItems={duplicationMaxItems}
            kitItemsCount={item?.isKit ? item.kitItemsCount : 0}
          />, rootElement)
    )}

  </div>
}

export default observer(DuplicateAction)
