import { CloseButton } from '@siteone/pagebuilder-components'
import { Icon } from '@siteone/pagebuilder-ui'
import { Image } from '@siteone/react-img-microservice'
import getOr from 'lodash/fp/getOr'
import React from 'react'
import Lottie from 'react-lottie-player/dist/LottiePlayerLight'
import styles from './style.scss'

const ImageRow = ({ tag, width, height, ...props }) => <img {...props} alt="preview" />
const getUrl = getOr('', 'url')
const getSelectedVideoId = selectedMedia => {
  if (typeof selectedMedia === 'string' || typeof selectedMedia === 'number') {
    return `${selectedMedia}`
  }

  if (selectedMedia && typeof selectedMedia === 'object') {
    return `${selectedMedia.id ||
      selectedMedia.videoId ||
      selectedMedia.value ||
      selectedMedia.returnValue ||
      (selectedMedia.props && selectedMedia.props.id) ||
      ''}`
  }

  return ''
}

const Thumb = ({
  customIconComponent,
  selectedMedia,
  type,
  setOpen,
  removeImage,
  withImageProvider,
  videoThumbnails = {},
}) => {
  /**
   * default Icon component, use pagebuilder UI if not specified
   */
  const url = getUrl(selectedMedia)
  const isSvg = url.includes('.svg')
  const isLottie = url.includes('.json')
  const IconComponent = customIconComponent || Icon
  const ImageComponent = (withImageProvider && !isSvg) ? Image : !isLottie ? ImageRow : 'div'
  const name = url.split('/').pop()
  const selectedVideoId = getSelectedVideoId(selectedMedia)
  const videoThumbnailUrl =
    (selectedMedia && selectedMedia.props && selectedMedia.props.thumbnailUrl) ||
    videoThumbnails[selectedVideoId]

  return (
    <div className={styles.thumb}>
      <div onClick={() => setOpen(true)} className={styles.pointer}>
        {type === 'image' && (
          <React.Fragment>
            {isLottie
              ? (
                <Lottie
                  path={url}
                  style={{ width: 125, height: 125 }}
                  play
                />
              )
              : (
                <ImageComponent src={selectedMedia.url} className={styles.img} width={125} height={125} />
              )
            }
            {name && <p className={styles.thumbName}>{name}</p>}
          </React.Fragment>
        )}
        {type === 'icon' && (
          <IconComponent name={selectedMedia} color="editable" />
        )}
        {type === 'video' && (
          <React.Fragment>
            {videoThumbnailUrl ? (
              <img src={videoThumbnailUrl} alt={selectedVideoId} style={{ maxWidth: 125, maxHeight: 125 }} />
            ) : (
              <Icon name="media/Video" color="editable" size={56} />
            )}
          </React.Fragment>
        )}
      </div>

      <div className={styles.remove}>
        <CloseButton onClick={() => removeImage('')} />
      </div>
    </div>
  )
}

export default Thumb
