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, useMemo } from "react"
import "./ProgressBar.scss"
import { MediaSegment } from './RecordingView';

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

interface SegmentBox {
  endTime: number,
  startTime: number,
  order: number,
}
interface CurrentHover {
  index: number,
  minX: number,
  maxX: number
}

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<SegmentBox[]>([]);

  const [dragged, setDragged] = useState<number>(-1);

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

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

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

  useEffect(() => {
    const order = props.videos.length
    if (order) {
      const { endTime, startTime } = props.videos.lastElement();
      setOrdered(prevOrdered => {
        return [...prevOrdered, { endTime, startTime , order }];
      });
    }
    // }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 = (segId: number): CurrentHover | null => {
    // get the segId of the segment that will become the new bounding area
    const rect = progressBarRef.current?.children[segId].getBoundingClientRect()
    if (rect == null) return null
    return {
      index: segId,
      minX: rect.x,
      maxX: rect.x + rect.width,
    }
  }
  
  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
    console.log('pointer down')
    // don't move the videobox element
    e.stopPropagation()

    // get the segment the user clicked on to be dragged
    const clickedSegment = e.target as HTMLDivElement & EventTarget

    // get the profess bar ro add event listeners
    // don't do anything if null
    const progressBar = progressBarRef.current
    if (progressBar == null || clickedSegment.id === progressBar.id) return
    progressBar.setPointerCapture(e.pointerId)

    const rect = clickedSegment.getBoundingClientRect()
    // id for segment is like 'segment-1' or 'segment-10', 
    // so this works to get the id
    const segId = parseInt(clickedSegment.id.split('-')[1])
    // set the selected segment to be the one dragged
    setDragged(segId)

    // this is the logic for storing the lower X bound and upper X bound
    // to know whether a swap is needed between two segments
    let lastHover: CurrentHover = {
      index: segId,
      minX: rect.x,
      maxX: rect.x + rect.width,
    }

    // create the div element that tracks the cursor
    const detchedSegment = document.createElement("div")
    initDeatchSegment(detchedSegment, rect);

    function updateSegmentOrder(event: PointerEvent): void{
      event.stopPropagation();

      followCursor(event, detchedSegment, rect)

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

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

    progressBar.addEventListener('pointermove', updateSegmentOrder)
    progressBar.addEventListener('pointerup', () => {
      progressBar.removeEventListener('pointermove', updateSegmentOrder), { once : true }
      // clickedSegment.style.position = clickedSegment.style.zIndex = 'inherit';
      // progressBar.removeEventListener('pointermove', updateSegmentOrder), { once: true }
      // clickedSegment.style.backgroundColor = 'red';
      console.log('removed dot')
      detchedSegment.remove()
      setDragged(-1);
    }, { once: true })
  }


  const initDeatchSegment = (dot: HTMLDivElement, rect: DOMRect) => {
    dot.classList.add("segment-selected")
    dot.style.transitionDuration = '0s';
    dot.style.position = 'absolute';
    dot.style.zIndex = '999';
    dot.style.width = `${rect.width}px`;
    dot.style.height = `${rect.height}px`;
    dot.style.left = `${rect.x}px`;
    dot.style.top = `${rect.y}px`;
    document.body.append(dot)
  }
  const cleanupDetachSegment = (dot: HTMLDivElement) => {
    dot.remove()
  }
  const followCursor = (event: PointerEvent, dot: HTMLDivElement, rect: DOMRect): void => {
    // event.stopPropagation()
    // const { width, height } = dot.getBoundingClientRect()
    const { width, height } = rect;
    dot.style.left = `${event.clientX - width/2}px`;
    dot.style.top = `${event.clientY - height/2}px`;
  }


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