"use client"

import { Drawer } from "antd"
import classNames from "classnames"
import { DrawerCss } from "../Calendar/style"
import { useEffect, useRef, useState } from "react"
import ReactPlayer from "react-player"
import { useRecoilState } from "recoil"
import { typePlayVideoState, videoPlayingState } from "@/recoil/video"
import { InputRangeCss } from "./style"
import { IIcons } from "@/type/Video"
import Image from "next/image"
import { isEmpty } from "lodash"

type IProps = {
  listVideo: any
  video: any
  isOpen: boolean
  setOpen: (value: boolean) => void
}

export default function VideoDetail({ listVideo, video, isOpen, setOpen }: IProps) {
  const playerRef = useRef<any>(null)
  const [played, setPlayed] = useState(0)
  const [playedSeconds, setPlayedSeconds] = useState(0)
  const [duration, setDuration] = useState(0)
  const [remainingTime, setRemainingTime] = useState(0)
  const [defaulPlay, setDefaulPlay] = useRecoilState(typePlayVideoState)
  const [videoPlaying, setVideoPlaying] = useRecoilState(videoPlayingState)
  const [isDisabled, setIsDisabled] = useState(false)

  useEffect(() => {
    if (!isEmpty(video)) {
      setIsDisabled(false)
      setVideoPlaying({
        url: video?.file || "",
        id: video?.id,
        title: video?.title,
        description: video?.description,
      })
      setDefaulPlay((prevState) => ({
        ...prevState,
        isPause: true,
        iconPause: "/img/icon/ms_play.svg",
        iconShuffle: "/img/icon/ms_shuffle_outline.svg",
        iconRepeat: "/img/icon/ms_repeat_outline.svg",
      }))
    } else {
      setIsDisabled(true)
      setVideoPlaying({
        url: "",
        id: "",
        title: "",
        description: "",
      })
      setDefaulPlay((prevState) => ({
        ...prevState,
        iconPause: "/img/icon/ms_pause.svg",
        iconShuffle: "/img/icon/ms_shuffle.svg",
        iconRepeat: "/img/icon/ms_repeat.svg",
      }))
    }
  }, [video, isDisabled])

  useEffect(() => {
    if (played === 1) {
      setRemainingTime(duration)
      setPlayedSeconds(0)
    } else {
      setRemainingTime(duration - playedSeconds)
    }
  }, [playedSeconds, duration, played])

  const formatTime = (seconds: any) => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = Math.floor(seconds % 60)

    return `${minutes < 10 ? "0" : ""}${minutes}:${remainingSeconds < 10 ? "0" : ""}${remainingSeconds}`
  }

  const renderIcon = (propsIcon: IIcons) => {
    return (
      <div
        className={`w-8 flex items-center justify-center gap-3 ${propsIcon?.classNameBox || ""}`}
        onClick={isDisabled ? (e) => e.preventDefault() : propsIcon?.onClick}>
        <Image
          src={propsIcon?.url_image}
          alt={propsIcon?.alt_image || ""}
          width={propsIcon?.width_image || 300}
          height={propsIcon?.height_image || 300}
          className={`aspect-square ${(!isDisabled && "hover:scale-[1.1]") || ""} ${propsIcon?.classNameImage || ""}`}
        />
      </div>
    )
  }

  const handleEnded = () => {
    const currentIndex = listVideo?.findIndex((item: any) => item?.id === videoPlaying?.id)

    if (defaulPlay?.isShuffle && defaulPlay?.isRepeat) {
      handleRandom()
    } else if (currentIndex < listVideo?.length || defaulPlay?.isRepeat) {
      handleNext()
    }
  }

  const handlePlayPause = () => {
    setDefaulPlay((prevState) => ({
      ...prevState,
      iconPause: prevState.isPause ? "/img/icon/ms_pause.svg" : "/img/icon/ms_play.svg",
      isPause: !prevState?.isPause,
    }))
  }

  const handleProgress = (progress: any) => {
    setPlayed(progress.played)
  }

  const handleSeek = (e: any) => {
    const seekTo = parseFloat(e.target.value)
    playerRef.current.seekTo(seekTo)
    setPlayed(seekTo)
  }

  const handleForward = () => {
    const newPlayed = Math.min(played + 10 / duration, 1)
    setPlayed(newPlayed)
    playerRef.current.seekTo(newPlayed)
  }

  const handleBackward = () => {
    const newPlayed = Math.max(played - 10 / duration, 0)
    setPlayed(newPlayed)
    playerRef.current.seekTo(newPlayed)
  }

  const handleNext = () => {
    setVideoPlaying((pre) => {
      const currentIndex = listVideo?.findIndex((item: any) => item?.id === pre?.id)
      const nextIndex = (currentIndex + 1) % listVideo?.length
      const songNext = listVideo?.[nextIndex]

      return { url: songNext?.file || "", id: songNext?.id || "", title: songNext?.title || "", description: songNext?.description || "" }
    })
  }

  const handlePrevious = () => {
    setVideoPlaying((pre) => {
      const currentIndex = listVideo?.findIndex((item: any) => item?.id === pre?.id)
      const prevIndex = (currentIndex - 1 + listVideo?.length) % listVideo?.length
      const songPre = listVideo?.[prevIndex]

      return { url: songPre?.file || "", id: songPre?.id || "", title: songPre?.title || "", description: songPre?.description || "" }
    })
  }

  const handleRandom = () => {
    setVideoPlaying(() => {
      const randomIndex = Math.floor(Math.random() * listVideo?.length)
      const songPre = listVideo[randomIndex]

      return { url: songPre?.file || "", id: songPre?.id || "", title: songPre?.title || "", description: songPre?.description || "" }
    })
  }

  return (
    <Drawer
      className={classNames(``, DrawerCss)}
      closable
      destroyOnClose
      title={<p>Video Info</p>}
      placement="right"
      open={isOpen}
      onClose={() => setOpen(false)}
      width={630}>
      <div className="relative flex flex-col justify-center text-center h-full">
        <div className="grow aspect-video">
          <ReactPlayer
            ref={playerRef}
            url={videoPlaying?.url}
            playing={Boolean(defaulPlay?.isPause)}
            width="100%"
            height="100%"
            onProgress={(progress) => {
              setPlayedSeconds(progress.playedSeconds)
              handleProgress(progress)
            }}
            onDuration={(duration) => setDuration(duration)}
            onEnded={handleEnded}
            loop={false}
          />
        </div>
        <div>
          <p className="text-lg leading-[25px] text-[var(--secondary-100)] font-bold mt-6 mb-[2px]">{`${
            isDisabled ? "--------------" : videoPlaying?.title
          }`}</p>
          <div
            className="text-sm font-light text-[var(--secondary-100)] mb-6"
            dangerouslySetInnerHTML={{ __html: isDisabled ? "---------" : videoPlaying?.description }}></div>

          <div className={classNames("w-full mb-3", InputRangeCss)}>
            <input
              type="range"
              min={0}
              max={1}
              step="0.01"
              value={played}
              onChange={handleSeek}
              style={
                {
                  "--progress": `${played * 100}%`,
                  "--inputRangeColor": `${isDisabled ? "#D1D5DB" : "#f59e0b"}`,
                  pointerEvents: isDisabled ? "none" : "auto",
                } as React.CSSProperties
              }
            />
          </div>
          <div className="flex justify-between mb-3">
            <span>{isDisabled ? formatTime(0) : formatTime(playedSeconds)}</span>
            <span>{isDisabled ? formatTime(0) : `${playedSeconds === 0 ? "" : "-"}${formatTime(remainingTime)}`}</span>
          </div>
          <div className="flex justify-between items-center">
            {renderIcon({
              url_image: defaulPlay?.iconShuffle,
              alt_image: "Shuffle",
              onClick: () => {
                setDefaulPlay((prevState) => ({
                  ...prevState,
                  iconShuffle:
                    prevState.iconShuffle === "/img/icon/ms_shuffle_outline.svg" && prevState?.isShuffle
                      ? "/img/icon/ms_shuffle.svg"
                      : "/img/icon/ms_shuffle_outline.svg",
                  isShuffle: !prevState?.isShuffle,
                }))
              },
            })}
            {renderIcon({
              url_image: defaulPlay?.iconPrevious,
              alt_image: "Previous",
              onClick: () => {
                handlePrevious()
              },
            })}
            {renderIcon({
              url_image: defaulPlay?.iconBackward,
              alt_image: "Backward",
              onClick: () => {
                handleBackward()
              },
            })}
            {renderIcon({
              url_image: defaulPlay?.iconPause,
              alt_image: "Pause",
              classNameBox: "!w-14",
              onClick: () => {
                handlePlayPause()
              },
            })}
            {renderIcon({
              url_image: defaulPlay?.iconForward,
              alt_image: "Forward",
              onClick: () => {
                handleForward()
              },
            })}
            {renderIcon({
              url_image: defaulPlay?.iconNext,
              alt_image: "Next",
              onClick: () => {
                handleNext()
              },
            })}
            {renderIcon({
              url_image: defaulPlay?.iconRepeat,
              alt_image: "Repeat",
              onClick: () => {
                setDefaulPlay((prevState) => ({
                  ...prevState,
                  iconRepeat:
                    prevState.iconRepeat === "/img/icon/ms_repeat_outline.svg" && prevState?.isRepeat
                      ? "/img/icon/ms_repeat.svg"
                      : "/img/icon/ms_repeat_outline.svg",
                  isRepeat: !prevState?.isRepeat,
                }))
              },
            })}
          </div>
        </div>
      </div>
    </Drawer>
  )
}
