import { forwardRef } from 'react'

import { isIOS } from 'config/userAgent'

import type { Props } from './hooks'
import { useVideoPlayer } from './hooks'
import { Video } from './styled'

/**
 * Низкоуровневый компонент для декларативной работы с HTMLVideoElement
 * ```ts
 * например старт и пауза плеера вместо
 * video.play() | video.pause()
 *
 * контролируем через пропс playing
 * <VideoPlayer playing={true | false} />
 * ```
 */
export const VideoPlayer = forwardRef<HTMLVideoElement, Props>((props: Props, ref) => {
  const {
    className,
    controls,
    crossOrigin,
    height,
    hidden,
    muted,
    onEnded,
    onError,
    onPause,
    onPlay,
    onPlaying,
    onWaiting,
    src,
    width,
  } = props
  const {
    handleDurationChange,
    handleLoadedChange,
    handlePlayedChange,
    handleReady,
    videoRef,
  } = useVideoPlayer({ ...props, ref })
  return (
    <Video
      autoPlay={isIOS}
      playsInline
      className={className}
      width={width}
      height={height}
      hidden={hidden}
      ref={videoRef}
      src={src}
      muted={muted}
      onCanPlayThrough={handleReady}
      onTimeUpdate={handlePlayedChange}
      onProgress={handleLoadedChange}
      onEnded={onEnded}
      onDurationChange={handleDurationChange}
      onPlay={onPlay}
      onPause={onPause}
      onError={onError}
      onWaiting={onWaiting}
      onPlaying={onPlaying}
      crossOrigin={crossOrigin}
      controls={controls}
    />
  )
})
