import './VideoUpload.scss'
import { UploadedUppyFile, UploadResult } from '@uppy/core'
import Progress from 'components/Progress'
import UppyUpload from 'components/UppyUpload'
import React, { useEffect, useState } from 'react'
import { MediaUpload } from 'redux/Common/types'
import { getVideoDuration } from 'utils/photo'
import { Text } from 'components/Typography'
import Button from 'antd/lib/button'
import { formatMinuteSecondWithUnit } from 'utils/date'
import { ReactComponent as AddIcon } from 'icons/dark/add-blue.svg'
import { ReactComponent as TimeIcon } from 'icons/time.svg'
import { ReactComponent as PlayIcon } from 'icons/play-circle.svg'
import ReactPlayer from 'react-player'
import { Row } from 'antd/lib/grid'
import Loading from 'components/Loading'
import { retry } from 'utils/retry'
import isEmpty from 'lodash/isEmpty'
import { useWindowEvent } from 'hooks/useWindowEvent'
import classNames from 'classnames'
import { Icon } from 'components/Icon'
import config from 'config'

interface Props {
  disableUpload?: boolean
  video: MediaUpload
  onUploadSuccess: (file: MediaUpload) => void
  onRemove: (file: MediaUpload) => void
}

const VideoUpload: React.FC<Props> = ({
  disableUpload = false,
  video,
  onUploadSuccess
}) => {
  const [contentVideo, setContentVideo] = useState<MediaUpload>({})
  const [loading, setLoading] = useState(false)
  const [loadingPercent, setLoadingPercent] = useState(0)
  const [forceReset, setForceReset] = useState(false)
  const [isUploadError, setIsUploadError] = useState(false)
  const [videoReady, setVideoReady] = useState(false)
  const [videoPlaying, setVideoPlaying] = useState(false)
  const [draftFileUploadSuccess, setDraftFileUploadSuccess] =
    useState<UploadedUppyFile<any, any>>()

  const playerRef = React.createRef<any>()

  const videoUploadClass = classNames({
    'on-demand-editor__video-upload': true
  })

  const focusTabOnBrowser = () => {
    if (
      !draftFileUploadSuccess ||
      (videoReady && !isEmpty(contentVideo)) ||
      (videoReady && !isEmpty(video))
    )
      return
    handleFileUploadSuccess(draftFileUploadSuccess)
  }
  useWindowEvent('focus', focusTabOnBrowser)

  useEffect(() => {
    setContentVideo(video)
    return () => {}
  }, [video])

  const onCompleteUpload = async (result: UploadResult<any>) => {
    const videoUploaded =
      Array.isArray(result.successful) && result.successful.length > 0
        ? result.successful[0]
        : undefined
    setDraftFileUploadSuccess(videoUploaded)
    videoUploaded && (await handleFileUploadSuccess(videoUploaded))
  }

  const handleFileUploadSuccess = async (file: UploadedUppyFile<any, any>) => {
    try {
      setIsUploadError(false)
      setVideoReady(false)
      const duration = await retry<number>(3, 1000, () =>
        getVideoDuration(file.data)
      )
      let media: MediaUpload = {}
      if (file.uploadURL) {
        media = {
          fileName: file.name,
          url: file.uploadURL,
          duration: duration,
          poster: `${config.service.assetUrl}/assets/images/talent-demo.png`
        }
      } else {
        media = {
          fileName: undefined,
          loading: false,
          duration: duration
        }
      }
      setContentVideo(media)
      onUploadSuccess(media)
    } catch (ex) {
      console.error('onCompleteUpload error:', ex)
    } finally {
      setLoading(false)
    }
  }

  const handleForceResetUppy = () => {
    setIsUploadError(false)
    setForceReset(false) // trigger to reset uppy container
    setTimeout(() => {
      setForceReset(true)
    }, 100)
  }

  const handleChangeFile = () => {
    handleForceResetUppy()
    setTimeout(() => {
      ;(
        document.getElementsByClassName(
          'uppy-DragDrop-container'
        )[0] as HTMLButtonElement
      ).click()
    }, 150)
  }

  const handleUploadError = (args: any) => {
    console.error('handleUploadError: ', { args })
    setLoading(false)
    setVideoReady(false)
    setIsUploadError(true)
  }

  const onVideoReady = () => {
    setVideoReady(true)
  }

  return (
    <React.Fragment>
      <div className="d--block">
        <Text className="d--block" preset="semibold18">
          Video
        </Text>
        <Text className="m__t--8" preset="regular14">
          Upload videos that match the trend that will get a lot of purchases
          for you.
        </Text>
      </div>
      <UppyUpload
        className={videoUploadClass}
        isShowPreview={!!contentVideo.url}
        maxFiles={1}
        acceptFiles={['video/mp4', 'video/x-m4v', 'video/*']}
        forceReset={forceReset}
        durationRestrict={60}
        onComplete={result => onCompleteUpload(result)}
        setLoading={value => setLoading(value)}
        setLoadingPercent={value => setLoadingPercent(value)}
        onUploadError={args => handleUploadError(args)}
      >
        {loading ? (
          <Progress value={loadingPercent} />
        ) : contentVideo.url ? (
          <React.Fragment>
            <div
              className={classNames({
                'video-preview-wrapper': true,
                'video-preview-wrapper__disable-upload': disableUpload
              })}
            >
              <div className="video-preview-wrapper__btn-actions--mobile">
                <Text>Edit</Text>
              </div>
              {!videoPlaying && (
                <div
                  className="video-preview-wrapper__btn-actions animate__animated animate__fadeIn"
                  onClick={
                    disableUpload ? () => setVideoPlaying(true) : undefined
                  }
                >
                  {!disableUpload ? (
                    <React.Fragment>
                      <Button
                        className="video-preview-wrapper__btn-actions--change m__b--16"
                        onClick={() => {
                          setVideoPlaying(true)
                        }}
                      >
                        Play
                      </Button>
                      <Button
                        className="video-preview-wrapper__btn-actions--change"
                        onClick={() => handleChangeFile()}
                      >
                        Change
                      </Button>
                    </React.Fragment>
                  ) : (
                    <Button
                      className="video-preview-wrapper__btn-actions--play m__b--16"
                      onClick={() => {
                        setVideoPlaying(true)
                      }}
                    >
                      <PlayIcon />
                    </Button>
                  )}
                </div>
              )}
              <ReactPlayer
                ref={playerRef}
                className="react-player"
                playing={videoPlaying}
                url={contentVideo?.url as string}
                width="100%"
                height="100%"
                controls
                onPause={() => {
                  setVideoPlaying(false)
                }}
                onPlay={() => {
                  setVideoPlaying(true)
                }}
                onReady={onVideoReady}
              />
              {disableUpload && (
                <div className="video-preview-wrapper__warning">
                  <Icon name="warning" width={18} height={18} />
                  <Text
                    preset="regular14"
                    className="text--black text__line-height--22"
                  >
                    Someone has already purchased this video so you cannot
                    update it
                  </Text>
                </div>
              )}
            </div>
          </React.Fragment>
        ) : (
          <span className="video-content__add-icon">
            {isUploadError && <p>Upload error. Please try again !!</p>}
            <AddIcon />
          </span>
        )}
        {!videoReady && contentVideo.url && (
          <div className="video-loading">
            <Loading />
          </div>
        )}
      </UppyUpload>

      {!!contentVideo?.duration && contentVideo?.duration !== 0 && (
        <Row className="fullwidth" align="middle" justify="center">
          <TimeIcon />
          <Text className="m__l--4">
            {contentVideo?.duration &&
              formatMinuteSecondWithUnit(contentVideo?.duration)}
          </Text>
        </Row>
      )}
    </React.Fragment>
  )
}

export default React.memo(VideoUpload)
