import { useParams } from 'react-router-dom'
import './lesson_details.css'
import { lessons_data } from './data'
import { useEffect, useRef, useState } from 'react'
function LessonDetails() {
  const param = useParams()
  const [lesson, setLesson] = useState()
  const lessons = lessons_data
  const [play, setPlay] = useState(false)
  const [mute, setMute] = useState(false)
  const [fullScreen, setFullScreen] = useState(false)
  const videoRef = useRef(null)
  const [currentTime, setCurrentTime] = useState(0)
  const [duration, setDuration] = useState(0)
  const progressPercentage = duration > 0 ? (currentTime / duration) * 100 : 0
  const formateTime = (time) => {
    let m = Math.floor(time / 60)
    let s = Math.floor(time % 60)
      .toString()
      .padStart(2, '0')
    return `${m}:${s}`
  }

  const play_video = () => {
    if (play) {
      videoRef.current.pause()
    } else {
      videoRef.current.play()
    }
    setPlay(!play)
  }
  const skip = (seconds) => {
    if (videoRef.current) {
      videoRef.current.currentTime += seconds
    }
  }
  const toggleFullScreen = () => {
    if (!videoRef.current) return
    if (document.fullscreenElement) {
      document.exitFullscreen()
    } else {
      videoRef.current.requestFullscreen()
    }
    setFullScreen(!fullScreen)
  }
  useEffect(() => {
    let x = lessons[0].lessons.find(
      (l) => parseInt(l.id) === parseInt(param.lessonId)
    )
    console.log('x=>', x)
    if (x) setLesson(x)
  }, [param])
  const handleLoadedMetadata = () => {
    console.log('duration loaded:', videoRef.current.duration)
    setDuration(videoRef.current.duration)
  }
  const handleTimeUpdate = () => {
    if (videoRef.current && !isDragging)
      setCurrentTime(videoRef.current.currentTime)
  }
  const [isDragging, setIsDragging] = useState(false)
  const handleSeek = (e) => {
    if (videoRef.current) {
      const progressBar = e.currentTarget
      const clickPosition = e.nativeEvent.offsetX
      //    console.log("progressBar=>",progressBar)
      //   console.log("mousePosition=>",clickPosition)
      const percentage = clickPosition / progressBar.offsetWidth
      const newTime = percentage * duration
      videoRef.current.currentTime = newTime
      setCurrentTime(newTime)
    }
  }

  const handleMouseDown = () => {
    setIsDragging(true)
  }

  const handleMouseUp = () => {
    setIsDragging(false)
  }

  const handleMouseMove = (e) => {
    // console.log("in function ")
    if (isDragging && videoRef.current) {
      console.log('in function')
      const progressBar = e.currentTarget
      const mousePosition = e.nativeEvent.offsetX
      const percentage = mousePosition / progressBar.offsetWidth
      console.log('progressBar=>', progressBar)
      console.log('mousePosition=>', mousePosition)
      const newTime = percentage * duration
      videoRef.current.currentTime = newTime
      setCurrentTime(newTime)
    }
  }
  return (
    <>
      {lesson && (
        <div className="lesson_details">
          <p>
            <span>المواد</span>
            <span>{`>`}</span>
            <span>{lesson.subject}</span>
            <span>{`>`}</span>
            <span className="l_title">{lesson.title}</span>
          </p>
          <div className="lesson_video">
            <button
              onClick={() => play_video()}
              className={play ? 'hidden play_b' : 'play_b'}
            >
              {play ? (
                <i className="fa-solid fa-pause"></i>
              ) : (
                <i className="fa-solid fa-play"></i>
              )}
            </button>
            <div className="custom_controlls">
              <div
                className="linetime"
                onClick={handleSeek}
                onMouseDown={handleMouseDown}
                onMouseUp={handleMouseUp}
                onMouseMove={handleMouseMove}
                onMouseLeave={handleMouseUp}
              >
                <span
                  style={{
                    width: `${progressPercentage}%`,
                    height: '100%',

                    transition: isDragging ? 'none' : 'width 0.1s ease',
                  }}
                ></span>
              </div>
              <div className="custom_controlls_contain">
                <div className="left_part">
                  <button onClick={() => play_video()}>
                    {play ? (
                      <i className="fa-solid fa-pause"></i>
                    ) : (
                      <i className="fa-solid fa-play"></i>
                    )}
                  </button>
                  <button onClick={() => skip(-10)}>
                    <i className="fa-solid fa-arrow-rotate-left skip "></i>
                  </button>

                  <button onClick={() => skip(+10)}>
                    {' '}
                    {/* hhhhh */}
                    <i className="fa-solid fa-arrow-rotate-right skip"></i>
                  </button>
                  <button
                    onClick={() => {
                      setMute(!mute)
                    }}
                  >
                    {mute ? (
                      <i className="fa-solid fa-volume-xmark"></i>
                    ) : (
                      <i className="fa-solid fa-volume-high"></i>
                    )}
                  </button>
                  <span className="">
                    {formateTime(currentTime)} / {formateTime(duration)}
                  </span>
                </div>
                <div className="right_part">
                  <span className="quality">HD</span>
                  <button>
                    <i className="fa-solid fa-gear"></i>{' '}
                  </button>
                  <button onClick={() => toggleFullScreen()}>
                    {fullScreen ? (
                      <i className="fa-solid fa-compress"></i>
                    ) : (
                      <i className="fa-solid fa-expand"></i>
                    )}
                  </button>
                </div>
              </div>
            </div>
            <video
              controls={false}
              ref={videoRef}
              muted={mute}
              preload="metadata"
              onLoadedMetadata={handleLoadedMetadata}
              onTimeUpdate={handleTimeUpdate}
            >
              <source src={lesson.videoUrl} />
            </video>
          </div>
          <div className="about_lesson">
            <h3>عن الدرس </h3>
            <p>{lesson.about}</p>
          </div>
        </div>
      )}
    </>
  )
}
export default LessonDetails
