import * as React from 'react'
import classnames from 'classnames'
import { Link } from 'react-router-dom'
import { Product } from '@dollarshaveclub/types'
import { PriceAddButton } from '../Buttons/PriceAddButton'
import Imgix from 'react-imgix'
import { Tray } from '../Tray'
import { TileOverlay } from '../ProductTileOverlay'

type Props = Readonly<{
  className?: string
  product: Product
  priceData?: PriceData
  onClickAdd?: (product: Product) => void
  handleShouldUpdateToRestock?: (
    product: Product,
    shouldRestock: boolean
  ) => Promise<boolean>
  onClickRemove?: (sku: string) => void
  onImgClick?: (product: Product) => void
  viewDetailsLink?: string
  framed?: boolean
  recommended?: string
  showAddAnimation?: boolean
  isAdded?: boolean
  isLoading?: boolean
  isShowingOverlay?: boolean
  isLoadingOverlay?: boolean
  isAutoRestock?: boolean
  isSoldOut?: boolean
  showSize?: boolean
  showPriceComparison?: boolean
  showBaseNameOnly?: boolean
  dataTestId?: string
  childrenMiddle?: JSX.Element
  childrenBottom?: JSX.Element
  additionalButtonClasses?: string
}>

type PriceData = {
  formattedRetailPrice: string
  formattedPrice: string
}

const noop = () => {}

const ProductTileInline: React.FunctionComponent<Props> = ({
  className,
  product,
  priceData,
  onClickAdd,
  handleShouldUpdateToRestock,
  onClickRemove,
  onImgClick,
  showAddAnimation = false,
  isAdded = false,
  isLoading = false,
  isSoldOut = false,
  isShowingOverlay = false,
  isLoadingOverlay = false,
  isAutoRestock = false,
  viewDetailsLink,
  framed,
  showSize,
  showPriceComparison = false,
  showBaseNameOnly = false,
  recommended = false,
  dataTestId = 'product-button',
  childrenMiddle,
  childrenBottom,
  additionalButtonClasses,
}) => {
  const inlineProductTileClasses = classnames(
    'ui-product-tile--inline ui-bg__paper--lightest ui-position--relative ui-text--center',
    className,
    {
      'ui-product-tile--inline__framed': framed,
      'ui-product-tile--inline--recommended': recommended,
    }
  )
  const productImage = product.assets.productTile.file.url
  const price = priceData?.formattedPrice
  const retailPrice = priceData?.formattedRetailPrice
  const buttonClasses = classnames('ui-price-btn--mb', additionalButtonClasses)
  const { newBadge = false } = product

  const handleShouldUpdateToRestockSubmit = (shouldRestock: boolean) => {
    if (!handleShouldUpdateToRestock) return
    handleShouldUpdateToRestock(product, shouldRestock)
  }

  const renderFrequencyText = () => {
    if (isAutoRestock) {
      return (
        <div>
          <span className="ui-icon ui-icon--repeat ui-mr--1" />
          <span>Auto-restock</span>
        </div>
      )
    } else {
      return (
        <div>
          <span className="ui-icon ui-icon--repeat-once ui-mr--1" />
          <span>Get this once</span>
        </div>
      )
    }
  }

  return (
    <div className={inlineProductTileClasses}>
      {recommended && (
        <div className="ui-product-tile--inline__recommendation-wrapper">
          {recommended}
        </div>
      )}
      <div className="ui-grid is-mobile is-vcentered ui-text--left ui-pt--1">
        <div className="ui-grid-col ui-text--center is-6-mobile is-4-tablet is-4-desktop">
          {newBadge && <span className="ui-product-tile__new-badge">New</span>}
          <Imgix
            className={classnames('ui-display--block', {
              'ui-cursor--pointer': !!onImgClick,
            })}
            disableLibraryParam
            imgixParams={{ fit: 'crop' }}
            height={140}
            width={140}
            src={productImage}
            htmlAttributes={{
              'alt': '',
              'role': 'presentation',
              'data-testid': 'product-image',
              'onClick': onImgClick ? () => onImgClick(product) : noop,
            }}
          />
        </div>
        <div className="ui-grid-col is-6-mobile is-8-tablet is-8-desktop">
          <div className="ui-product-tile__lockup">
            <div className="text-wrapper ui-product-tile--inline__detail-container">
              <div className="ui-color--paper-dark ui-product-tile--inline__product-name">
                {showBaseNameOnly
                  ? product.basename
                  : [product.modifier, product.basename].join(' ')}
              </div>
              {product.scent && (
                <div className="ui-text--sm ui-color--paper-medium ui-product-tile--inline__product-detail">
                  {product.scent}
                </div>
              )}
              {showSize && (
                <div className="ui-color--paper-light ui-text--sm ui-product-tile--inline__product-detail">
                  {product.sizeNumber} {product.abbrSizeUnit}
                </div>
              )}
              {viewDetailsLink && (
                <Link to={viewDetailsLink} className="ui-link ui-text--sm">
                  View Details
                </Link>
              )}
              {childrenBottom}
            </div>
            <div className="ui-display--inline-block">
              {childrenMiddle ||
                (price && onClickAdd && (
                  <PriceAddButton
                    {...{
                      product,
                      onClickAdd,
                      price,
                      dataTestId,
                      isLoading,
                      isAdded,
                      isSoldOut,
                      showAddAnimation,
                      onClickRemove,
                      additionalButtonClasses: buttonClasses,
                    }}
                  />
                ))}
              {(!isAdded || isLoading || showAddAnimation) &&
                showPriceComparison && (
                  <div
                    className={classnames('ui-text--sm', {
                      'ui-mb--1': !!childrenBottom,
                    })}
                  >
                    Regular: <s>{retailPrice}</s>
                  </div>
                )}
              {product.planEligible &&
                handleShouldUpdateToRestock &&
                isAdded &&
                !showAddAnimation &&
                !isLoading &&
                renderFrequencyText()}
            </div>
          </div>
        </div>
        <div className="ui-grid-col is-6-mobile is-8-tablet is-8-desktop">
          <div style={{ margin: '-15px 0' }}>
            <Tray
              padding={false}
              backdrop={false}
              isOpen={isShowingOverlay}
              position="right"
              isRelativePosition
              role="alertdialog"
              ariaLabel="Restock options"
              ariaDescId={`product-tile-inline-dialog-desc-for-${product.sku}`}
            >
              <TileOverlay
                handleShouldUpdateToRestock={handleShouldUpdateToRestockSubmit}
                isLoading={isLoadingOverlay}
                isVisible={isShowingOverlay}
                id={`product-tile-inline-dialog-desc-for-${product.sku}`}
              />
            </Tray>
          </div>
        </div>
      </div>
    </div>
  )
}

export default ProductTileInline
