import React, { useLayoutEffect, useRef, memo } from 'react'
import classNames from 'classnames'

type TileOverlayProps = {
  handleShouldUpdateToRestock: (autoRestock: boolean) => void
  isLoading: boolean
  isVisible: boolean
  id: string
}

const TileOverlayBase: React.FunctionComponent<TileOverlayProps> = ({
  handleShouldUpdateToRestock,
  isLoading,
  isVisible,
  id,
}) => {
  const updateAutoRestock = () => {
    handleShouldUpdateToRestock(true)
  }
  const keepOneTime = () => {
    handleShouldUpdateToRestock(false)
  }

  const buttonRef = useRef<HTMLButtonElement>(null)

  useLayoutEffect(() => {
    if (isVisible && buttonRef.current) {
      buttonRef.current.focus()
    }
  }, [isVisible])

  return (
    <div className="ui-product-tile__overlay ui-pr--2 ui-pl--2">
      <div
        id={id}
        role="alert"
        className="ui-font__primary--bold ui-product-tile__overlay-main-text"
      >
        Would you like us to send this in every box?
      </div>
      <button
        className={classNames('ui-btn ui-btn__primary', {
          'ui-loading-cover': isLoading,
        })}
        onClick={updateAutoRestock}
        disabled={isLoading}
        tabIndex={isVisible ? 0 : -1}
        ref={buttonRef}
      >
        Yes Please
      </button>
      <button
        className="ui-btn__link ui-link ui-product-tile__overlay-no-thanks"
        onClick={keepOneTime}
        tabIndex={isVisible ? 0 : -1}
      >
        No thanks
      </button>
    </div>
  )
}

export const TileOverlay = memo(TileOverlayBase)
