import React, { FC, memo, useRef, useState } from 'react'
import { LayoutChangeEvent, useWindowDimensions } from 'react-native'
import { runOnJS, useAnimatedReaction } from 'react-native-reanimated'
import { StoryVideoProps } from '../../core/dto/componentsDTO'

import * as Device from 'expo-device'

import { ResizeMode, Video } from 'expo-av'

const StoryVideo: FC<StoryVideoProps> = ({
	uri,
	paused,
	isActive,
	onLoad,
	onLayout,
	...props
}) => {
	try {
		// eslint-disable-next-line global-require

		const ref = useRef<any>(null)
		const { width: WIDTH, height: HEIGHT } = useWindowDimensions()

		const isTablet = Device.deviceType === Device.DeviceType.TABLET

		const [pausedValue, setPausedValue] = useState(!paused.value)

		const start = () => ref.current?.setPositionAsync(0)

		useAnimatedReaction(
			() => paused.value,
			(res, prev) => res !== prev && runOnJS(setPausedValue)(!res),
			[paused.value]
		)

		useAnimatedReaction(
			() => isActive.value,
			res => res && runOnJS(start)(),
			[isActive.value]
		)

		return (
			<Video
				ref={ref}
				style={{
					width: WIDTH,
					height: isTablet ? HEIGHT : undefined,
					aspectRatio: isTablet ? undefined : 0.5626,
				}}
				resizeMode={ResizeMode.COVER}
				{...props}
				source={{ uri }}
				shouldPlay={isActive.value}
				useNativeControls={false}
				isLooping={false}
				onLoad={() => onLoad((props?.duration || 0) * 1000)}
				onLayout={(e: LayoutChangeEvent) =>
					onLayout(e.nativeEvent.layout.height)
				}
			/>
		)
	} catch (error) {
		return null
	}
}

export default memo(StoryVideo)
