import Feather from '@expo/vector-icons/Feather'
import { BlurView } from 'expo-blur'
import { Image as ExpoImage } from 'expo-image'
import { type VideoSource, VideoView } from 'expo-video'
import { StyleSheet, View } from 'react-native'
import { PressableOpacity } from 'src/components/common/PressableOpacity'
import { useVideo } from 'src/hooks/playback/PlaybackScope'
import { useScopedPlayer } from 'src/hooks/playback/useScopedPlayer'
import { ICON } from 'src/lib/icons'
import { useTheme } from 'tamagui'

type Props = {
  source: VideoSource
  height: number
  videoId: string
  previewUrl?: string | null
  blurhash?: string | null
}

const hasRealThumbnail = (url?: string | null): url is string =>
  typeof url === 'string' && url.length > 0 && !url.includes('no-preview.png')

const VideoPlayer = ({ source, height, videoId, previewUrl, blurhash }: Props) => {
  const { currentVideoId, playVideo } = useVideo()
  const theme = useTheme()
  const isCurrent = currentVideoId === videoId
  const { player, isPlaying } = useScopedPlayer({
    source,
    videoId,
    mode: 'feed',
    audible: true,
  })

  const onTogglePress = () => {
    if (isCurrent) playVideo(null)
    else playVideo(videoId)
  }

  // Show the poster whenever the video isn't actively rendering frames:
  // outside the preload window, paused, or not yet tapped. Unmount once
  // playback begins so the Image is not kept in memory over the VideoView.
  const showPoster = !isPlaying
  const posterUri = hasRealThumbnail(previewUrl) ? previewUrl : null
  const posterPlaceholder = blurhash ? { blurhash } : undefined

  return (
    <View
      style={{
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        height,
      }}
    >
      <PressableOpacity
        style={{
          width: '100%',
          height: '100%',
          justifyContent: 'center',
          alignItems: 'center',
        }}
        onPress={onTogglePress}
        activeOpacity={0.98}
      >
        <VideoView
          player={player}
          style={{ width: '100%', height: '100%' }}
          contentFit="cover"
          nativeControls={false}
          allowsPictureInPicture
        />

        {showPoster && (posterUri || posterPlaceholder) && (
          <ExpoImage
            source={posterUri ? { uri: posterUri } : null}
            placeholder={posterPlaceholder}
            placeholderContentFit="cover"
            contentFit="cover"
            transition={150}
            style={StyleSheet.absoluteFillObject}
            pointerEvents="none"
          />
        )}

        {!isPlaying && (
          <View
            style={{
              position: 'absolute',
              justifyContent: 'center',
              alignItems: 'center',
              borderRadius: 50,
              overflow: 'hidden',
              width: 60,
              height: 60,
            }}
          >
            <BlurView
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
              }}
              tint="dark"
              intensity={40}
            />
            <Feather
              name="play"
              size={ICON.xl}
              color={theme.colorInverse.val}
              style={{ marginLeft: 4 }}
            />
          </View>
        )}
      </PressableOpacity>
    </View>
  )
}

export default VideoPlayer
