import React, {useEffect, useRef, useState} from 'react';
import {StyleSheet, View} from 'react-native';
import Video from 'react-native-video';
import {Trimmer} from 'react-native-video-processing';
import {SCREEN_HEIGHT, SCREEN_WIDTH} from '../../utils';

interface TrimmerPlayerProps {
  source: string;
  videoStyles: Object;
  hideTrimmer: boolean;
  handleLoad: Function;
  onChangedEndpoints: Function;
  muted: boolean;
}

const TrimmerPlayer: React.FC<TrimmerPlayerProps> = ({
  source,
  videoStyles,
  hideTrimmer,
  handleLoad,
  onChangedEndpoints,
  muted,
}) => {
  // Stores the reference to player for seeking
  const playerRef = useRef<Video>();
  // Stores where the video is playing (seekTime)
  const [seekTime, setSeekTime] = useState<number>(0);
  const [paused, setPaused] = useState<boolean>(false);
  // Stores where the tracker is
  const [trackerTime, setTrackerTime] = useState<number>(0);
  // Stores start/end of desired trimmed video
  const [end, setEnd] = useState<number>(60);
  const [start, setStart] = useState<number>(0);

  useEffect(() => {
    playerRef.current?.seek(seekTime);
  }, [seekTime]);
  useEffect(() => {
    if (!paused && (trackerTime >= end || trackerTime < start)) {
      setTrackerTime(start);
      playerRef.current?.seek(start);
    }
  }, [trackerTime]);
  useEffect(() => {
    setSeekTime(start);
    setTrackerTime(start);
  }, [start]);
  useEffect(() => {
    setSeekTime(end);
    setTrackerTime(start);
  }, [end]);
  // Callback so parent knows where the trimming endpts are
  useEffect(() => onChangedEndpoints({end, start}), [end, start]);

  useEffect(() => {
    playerRef.current?.seek(0);
  }, [hideTrimmer]);

  return (
    <>
      <Video
        // link to descr and use of props of video player ->
        // https://github.com/react-native-video/react-native-video
        ref={(ref) => {
          playerRef.current = ref || undefined;
        }}
        source={{uri: source}}
        rate={1.0}
        volume={1.0}
        muted={muted}
        paused={paused}
        resizeMode={'contain'}
        repeat={true}
        onLoad={(payload) => {
          setEnd(payload.duration);
          handleLoad(payload.naturalSize);
        }}
        onProgress={(e) => {
          if (!paused) {
            setTrackerTime(e.currentTime);
          }
        }} // Callback every ~250ms with currentTime
        style={videoStyles}
        onTouchEnd={() => {
          setPaused((state) => !state);
        }}
      />
      {!hideTrimmer && (
        <View style={styles.trimmerContainer}>
          <Trimmer
            // link to descr and use of props for trimmer ->
            // https://github.com/shahen94/react-native-video-processing
            source={source}
            height={75}
            width={SCREEN_WIDTH}
            onTrackerMove={(e: {currentTime: number}) => {
              setPaused(true);
              setSeekTime(e.currentTime);
            }}
            currentTime={trackerTime}
            themeColor={'white'}
            thumbWidth={10}
            trackerColor={'white'}
            onChange={(e: {endTime: number; startTime: number}) => {
              setPaused(true);
              setEnd(e.endTime);
              setStart(e.startTime);
            }}
          />
        </View>
      )}
    </>
  );
};

const styles = StyleSheet.create({
  trimmerContainer: {
    position: 'absolute',
    bottom: SCREEN_HEIGHT * 0.1,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: 'red',
  },
});

export default TrimmerPlayer;
