import React from 'react'
import PropTypes from 'prop-types'
import { Typography, useThemeTokens, selectSystemProps } from '@telus-uds/components-base'
import styled from 'styled-components'
import videoText from '../../../videoText'
import { htmlAttrs } from '../../../../utils'

const [selectProps, selectedSystemPropTypes] = selectSystemProps([htmlAttrs])

const ProgressBarContainer = styled.div({
  display: 'flex',
  width: '100%',
  alignItems: 'center'
})

const sharedStyles = ({
  thumbHeight,
  thumbWidth,
  thumbBackground,
  trackGradientStart,
  trackGradientEnd
}) => ({
  thumb: {
    appearance: 'none',
    height: thumbHeight,
    width: thumbWidth,
    borderRadius: '50%',
    background: thumbBackground,
    cursor: 'pointer',
    marginTop: -3,

    '&:hover': {
      transform: 'scale(1.5)'
    }
  },
  track: (videoBufferDisplay) => ({
    width: '100%',
    height: 2,
    cursor: 'pointer',
    borderRadius: 1.3,
    background: `linear-gradient(to right, ${trackGradientStart} 0%,${trackGradientEnd} ${
      videoBufferDisplay - 0.01
    }% ,rgba(255,255,255,0.5) ${videoBufferDisplay}%)` // TODO: replace with opaque white from palette
  })
})

const StyledProgressBar = styled.input.attrs(({ videoCurrentTime }) => ({
  value: videoCurrentTime
}))(({ videoBufferDisplay, rangeBackground, ...sharedProps }) => ({
  width: '100%',
  cursor: 'pointer',
  padding: '5px 0',
  'input[type=range]&': {
    appearance: 'none',
    width: '100%',
    background: rangeBackground
  },

  'input[type=range]&:focus': {
    outline: 'none'
  },

  'input[type=range]&::-webkit-slider-thumb': sharedStyles(sharedProps).thumb,
  'input[type=range]&::-moz-range-thumb': {
    ...sharedStyles(sharedProps).thumb,
    border: 'none'
  },
  'input[type=range]&::-ms-thumb': {
    ...sharedStyles(sharedProps).thumb,
    margin: 0,
    border: 'none'
  },

  'input[type=range]&::-webkit-slider-runnable-track':
    sharedStyles(sharedProps).track(videoBufferDisplay),
  'input[type=range]&::-moz-range-track': sharedStyles(sharedProps).track(videoBufferDisplay),
  'input[type=range]&::-ms-track': {
    ...sharedStyles(sharedProps).track(videoBufferDisplay),
    margin: '6px 0',
    border: 'none'
  },

  'input[type=range]&::-ms-fill-lower': {
    background: rangeBackground
  },
  'input[type=range]&::-ms-tooltip': {
    display: 'none'
  }
}))

const StyledTimestamp = styled.span(({ margin }) => ({
  margin
}))
// TODO: unify with the helper from `VideoSplash`
function getTimestamp(duration) {
  const minutes = Math.floor(duration / 60)
  const seconds = Math.floor(duration - 60 * minutes)

  return `${minutes}:${seconds < 10 ? 0 : ''}${seconds}`
}

const VideoProgressBar = ({
  copy = 'en',
  videoLength,
  videoCurrentTime,
  videoBufferEnd,
  playing,
  setSeek,
  resetInactivityTimer,
  tokens,
  variant,
  ...rest
}) => {
  const {
    thumbHeight,
    thumbWidth,
    thumbBackground,
    timestampMarginLeft,
    timestampMarginRight,
    remainingTimestampMarginLeft,
    remainingTimestampMarginRight,
    trackGradientStart,
    trackGradientEnd,
    rangeBackground
  } = useThemeTokens('VideoProgressBar', tokens, variant, { playing })

  const videoProgressBar = React.createRef()

  const handleVideoSkip = () => {
    setSeek(videoProgressBar.current.value)
  }

  const videoBufferDisplay = (videoBufferEnd / videoLength) * 100

  const isVideoUnplayed = videoCurrentTime === -1
  const currentTime = isVideoUnplayed ? 0 : videoCurrentTime
  const remainingTime = isVideoUnplayed ? videoLength : videoLength - videoCurrentTime

  const currentTimestamp = getTimestamp(currentTime)
  const remainingTimestamp = getTimestamp(remainingTime)

  const sharedProps = {
    thumbWidth,
    thumbHeight,
    thumbBackground,
    trackGradientStart,
    trackGradientEnd,
    rangeBackground
  }

  return (
    <ProgressBarContainer {...selectProps(rest)}>
      <StyledTimestamp margin={`0 ${timestampMarginRight}px 0 ${timestampMarginLeft}px`}>
        <Typography variant={{ inverse: true }}>{currentTimestamp}</Typography>
      </StyledTimestamp>
      <StyledProgressBar
        aria-label={videoText[copy].videoProgressBarLabel}
        type="range"
        step="any"
        max={videoLength}
        videoCurrentTime={videoCurrentTime}
        onChange={handleVideoSkip}
        onFocus={resetInactivityTimer}
        videoBufferDisplay={videoBufferDisplay}
        ref={videoProgressBar}
        tabIndex="-1"
        {...sharedProps}
      />
      <StyledTimestamp
        margin={`0 ${remainingTimestampMarginRight}px 0 ${remainingTimestampMarginLeft}px`}
      >
        <Typography variant={{ inverse: true }}>{remainingTimestamp}</Typography>
      </StyledTimestamp>
    </ProgressBarContainer>
  )
}

VideoProgressBar.propTypes = {
  ...selectedSystemPropTypes,
  copy: PropTypes.oneOf(['en', 'fr']),
  videoLength: PropTypes.number.isRequired,
  videoCurrentTime: PropTypes.number.isRequired,
  videoBufferEnd: PropTypes.number.isRequired,
  setSeek: PropTypes.func.isRequired,
  resetInactivityTimer: PropTypes.func.isRequired
}

export default VideoProgressBar
