import React, {useEffect, useState} from 'react';
import Video from 'react-native-video';
import {Trimmer, ProcessingManager} from 'react-native-video-processing';
import {useRef} from 'react';

export const TrimmerPlayer: React.FC<{source: string; styles: Object}> = ({
  source,
  styles,
}) => {
  const playerRef = useRef<Video>();

  const [seekTime, setSeekTime] = useState<number>(0);
  const [paused, setPaused] = useState<boolean>(false);
  useEffect(() => {
    playerRef.current?.seek(seekTime);
  }, [seekTime]);

  const [trackerTime, setTrackerTime] = useState<number>(0);
  useEffect(() => {
    if (!paused && (trackerTime >= end || trackerTime < start)) {
      //console.log('trackerTime reset start', start);
      setTrackerTime(start);
      playerRef.current?.seek(start);
    }
  }, [trackerTime]);

  const [end, setEnd] = useState<number>(60);
  const [start, setStart] = useState<number>(0);
  useEffect(() => {
    setSeekTime(start);
    setTrackerTime(start);
  }, [start]);
  useEffect(() => {
    setSeekTime(end);
    setTrackerTime(end - 0.1);
  }, [end]);

  const trim = () => {
    ProcessingManager.trim(source, {
      startTime: start / 2, //need to divide by two for bug in module
      endTime: end,
      saveToCameraRoll: true, // default is false // iOS only
      saveWithCurrentDate: true, // default is false // iOS only
      quality: 'highest',
    }) // like VideoPlayer compress options
      .then((data: any) => console.log(data));
  };

  /*
  const [tempSource, setSource] = useState<string>(source);
  const getCompressedVideo = () => {
    console.log(source);
    //ProcessingManager.getVideoInfo(source, (info) => console.log('info', info));

    ProcessingManager.compress(source, {
      width: 720,
      height: 1280,
      bitrateMultiplier: 3,
      saveToCameraRoll: true, // default is false, iOS only
      saveWithCurrentDate: true, // default is false, iOS only
      minimumBitrate: 300000,
      removeAudio: true, // default is false
    }).then((data: string) => {
      //console.log('compressed', data);
      setSource(data);
    });
  };
  useEffect(() => {
    getCompressedVideo();
  }, []); */

  return (
    <>
      <Video
        ref={(ref) => {
          playerRef.current = ref || undefined;
        }}
        source={{uri: source}} // Looks for .mp4 file (background.mp4) in the given expansion version.
        rate={1.0} // 0 is paused, 1 is normal.
        volume={1.0} // 0 is muted, 1 is normal.
        muted={false} // Mutes the audio entirely.
        paused={paused} // Pauses playback entirely.
        //resizeMode="cover" // Fill the whole screen at aspect ratio.
        repeat={true} // Repeat forever.
        //onLoadStart={this.loadStart} // Callback when video starts to load
        onLoad={(payload) => {
          console.log(payload, source);
          setEnd(payload.duration);
        }} // Callback when video loads
        onProgress={(e) => {
          //console.log('progress', e.currentTime);
          if (!paused) {
            // make sure within bounds
            setTrackerTime(e.currentTime);
          }
        }} // Callback every ~250ms with currentTime
        //onEnd={() => console.log('end')} // Callback when playback finishes
        //onError={this.videoError} // Callback when video cannot be loaded
        style={styles}
        onTouchEnd={() => {
          //setPaused((state) => !state);
          trim();
        }}
      />
      <Trimmer
        source={source}
        height={100}
        width={350}
        onTrackerMove={(e) => {
          //console.log('trackerMove', e);
          setPaused(true);
          setSeekTime(e.currentTime);
        }} // iOS only
        // added .25 bc tracker is inaccurate
        currentTime={trackerTime + 0.25} // use this prop to set tracker position iOS only
        themeColor={'white'} // iOS only
        showTrackerHandle={true}
        thumbWidth={10} // iOS only
        trackerColor={'white'} // iOS only
        onChange={(e) => {
          //console.log('endsChange', e);
          setPaused(true);
          setEnd(e.endTime);
          setStart(e.startTime);
        }}
      />
    </>
  );
};
