import React, { useState, useRef, useEffect, useMemo } from 'react'
import { t } from '$themelocalization'
import { ButtonAria } from '$core-components'
import { Tooltip } from 'reactstrap-wc'
import './DraftIncludedProducts.scss'

const DraftIncludedProducts = ({ subItems, onTooltipChange }) => {
  const [showPopup, setShowPopup] = useState(false)
  const triggerRef = useRef(null)
  const [isMounted, setIsMounted] = useState(false)

  useEffect(() => {
    setIsMounted(true)
  }, [])

  if (!subItems || subItems.length === 0) {
    return null
  }

  const handleToggle = (nextState) => {
    setShowPopup(nextState)
    onTooltipChange?.(nextState)
  }

  const handleClick = () => {
    const next = !showPopup
    handleToggle(next)
  }

  const renderContent = () => (
    <div className="scroll-wrapper">
      {subItems.map((subItem, index) => (
        <div key={index} className="product-detail">
          <div className="product-name">{subItem.product?.name}</div>
          <div className="product-quantity">
            {subItem.quantity} {subItem.product?.unit?.Name || t('Drafts.Item.Items')}
          </div>
        </div>
      ))}
    </div>
  )

  return (
    <div className={`draft-sub-items ${showPopup ? 'tooltip-open' : ''}`}>
      <span className="draft-sub-items-trigger">
        <ButtonAria
          ref={triggerRef}
          className="button button-transparent title"
          onClick={handleClick}
        >
          {t('Drafts.Item.IncludedProducts', { count: subItems.length })}
        </ButtonAria>
      </span>

      {isMounted && triggerRef.current && (
      <Tooltip
        isOpen={showPopup}
        target={triggerRef.current}
        toggle={() => handleToggle(!showPopup)}
        placement="bottom-start"
        fade={false}
        autohide={false}
        trigger="hover click"
        delay={{ show: 0, hide: 150 }}
        className="draft-sub-items-tooltip"
        innerClassName="draft-sub-items-details show"
        popperClassName="draft-sub-items-tooltip-popper"
        container={document.body}
        modifiers={[
          { name: 'flip', enabled: false },
          { name: 'preventOverflow', options: { boundary: 'viewport' } },
          { name: 'offset', options: { offset: [0, 8] } },
        ]}
      >
        {renderContent()}
      </Tooltip>
      )}
    </div>
  )
}

export default DraftIncludedProducts
