import { resolveTxt } from 'dns';
import { videointelligence } from 'googleapis/build/src/apis/videointelligence';
import { isInteger } from 'lodash';
import * as React from 'react';
import { useEffect, useState, useCallback, useRef } from "react"
import "./ProgressBar.scss"
import { MediaSegment } from './RecordingView';

interface ProgressBarProps {
  videos: MediaSegment[],
  setVideos,
}

export function ProgressBar(props: ProgressBarProps) {

  const progressBarRef = useRef<HTMLDivElement | null>(null)

  // array for the order of video segments
  const [segments, setSegments] = useState<JSX.Element[]>([]);
  const [ordered, setOrdered] = useState<Object[]>([]);

  const [clicked, setClicked] = useState<number>(-1);

  // const totalTime = useMemo(() => props.videos.lastElement().endTime, [props.videos])

  const totalTime = () => props.videos.lastElement().endTime

  useEffect(() => {
    const segmentsJSX = ordered.map((vid, i) =>
      <div id={`segment-${i.toString()}`} className='segment' style={{ width: `${((vid.endTime - vid.startTime) / totalTime()) * 100}%`, backgroundColor: clicked === i ? 'inherit' : 'red', }}>{vid.order}</div>);
      
    setSegments(segmentsJSX)
  }, [clicked, ordered])

  useEffect(() => {
    setOrdered(props.videos.map((vid, order) => {
    //const { endTime, startTime } = vid
      // TODO: not tranfer the blobs around
      return { ...vid, order };
    }))
  }, [props.videos]);



      // const handleClick = (e: React.MouseEvent) => {
      //       let progressbar = document.getElementById('progressbar')!
      //       let bounds = progressbar!.getBoundingClientRect();
      //       let x = e.clientX - bounds.left;
      //       let percent = x / progressbar.clientWidth * 100

      //       for (let i = 0; i < props.marks.length; i++) {
      //             let start = i == 0 ? 0 : props.marks[i-1];
      //             if (percent > start && percent < props.marks[i]) {
      //                   props.playSegment(i)
      //                   // console.log(i)
      //                   // console.log(percent)
      //                   // console.log(props.marks[i])
      //                   break
      //             }
      //       }
      // }
  
  const updateLastHover = (index) => {
        // id for segment is like 'segment-1' or 'segment-10'
    const segId = index
    console.log(segId)
    const rect = progressBarRef.current?.children[segId].getBoundingClientRect()
    console.log(rect)
    return {
      index: segId,
      minX: rect.x,
      maxX: rect.x + rect.width,
    }
  }
  
  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) =>{
    // e.persist()
    // console.log('event', e)
    // don't move the videobox element
    e.stopPropagation()

    const progressBar = progressBarRef.current
    if (progressBar == null) return
    console.log('progressbar', progressBar)
    
    // progressBar.addEventListener('pointermove', updateSegmentOrder)


    const clickedSegment = e.target as HTMLDivElement & EventTarget

    const rect = clickedSegment.getBoundingClientRect()
    setClicked(parseInt(clickedSegment.id.split('-')[1]))
    let lastHover = {
      index: parseInt(clickedSegment.id.split('-')[1]),
      minX: rect.x,
      maxX: rect.x + rect.width,
    }

    // clickedSegment.style.backgroundColor = `inherit`;
    const dot = document.createElement("div")
    dot.classList.add("segment")
    dot.style.position = 'absolute';
    dot.style.zIndex = '999';
    dot.style.width = `${rect.width}px`;
    dot.style.height = `${rect.height}px`;
    document.body.append(dot)
    const dragSegment = (event: PointerEvent): void => {
      // event.stopPropagation()
      dot.style.left = `${event.clientX - rect.width/2}px`;
      dot.style.top = `${event.clientY - rect.height/2}px`;
     }

    const updateSegmentOrder = (event: PointerEvent): void => {
      event.stopPropagation();

      dragSegment(event)

      const oldIndex = lastHover.index
      const swapSegments = (newIndex) => {
        if (newIndex == null) return
        setOrdered(prevOrdered => {
          const cpy = [...prevOrdered]
          cpy[oldIndex] = cpy[newIndex]
          cpy[newIndex] = prevOrdered[oldIndex]
          return cpy
        })
        setClicked(newIndex)
      }

      const curX = event.clientX;
      if (curX < lastHover.minX && lastHover.index > 0) {
        swapSegments(lastHover.index - 1)
        lastHover = updateLastHover(lastHover.index - 1)
      }
      else if (curX > lastHover.maxX && lastHover.index < segments.length - 1) {
        swapSegments(lastHover.index + 1)
        lastHover = updateLastHover(lastHover.index + 1)
      }
     }

    progressBar.setPointerCapture(e.pointerId)
    progressBar.addEventListener('pointermove', updateSegmentOrder)
    progressBar.addEventListener('pointerup', (event) => {
      progressBar.removeEventListener('pointermove', updateSegmentOrder), { once: true }
      // clickedSegment.style.position = clickedSegment.style.zIndex = 'inherit';
      // progressBar.removeEventListener('pointermove', updateSegmentOrder), { once: true }
      // clickedSegment.style.backgroundColor = 'red';
      setClicked(-1);
      // updateSegmentOrder(event);
      dot.remove();
    })
  }

      return (
        <div className="progressbar" id="progressbar" onPointerDown={onPointerDown} ref={progressBarRef}>
                  {/* <div
                        className="progressbar done"
                        style={{ width: `${props.progress}%` }}
                  // onClick={handleClick}
                  ></div> */}
          {segments}
        </div>
      )
}