"use client";

import dynamic from "next/dynamic";
import { useEffect, useRef, useState } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  togglePlay,
  setCurrentTime,
  setDuration,
  setPiP,
} from "@/store/slices/playerSlice";
import { PiPButton } from "@/components/player/PiPButton";
import { CustomVideoPlayer } from "./CustomVideoPlayer";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const ReactPlayer = dynamic(() => import("react-player"), { ssr: false }) as any;

interface VideoPlayerProps {
  url: string;
  contentUploadType: string;
}

/* ── YouTube player (uses react-player + native iframe controls) ─────────── */
function YouTubePlayer({ url }: { url: string }) {
  const dispatch = useAppDispatch();
  const { isPlaying: reduxPlaying, volume, currentTime: resumeTime, isPiP } =
    useAppSelector((s) => s.player);

  const [playing, setPlaying]       = useState(reduxPlaying);
  const [buffering, setBuffering]   = useState(false);
  const [hovered, setHovered]       = useState(false);
  const [pipSupported, setPipSup]   = useState(false);

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const playerRef  = useRef<any>(null);
  const videoElRef = useRef<HTMLVideoElement | null>(null);
  const didSeekRef = useRef(false);

  useEffect(() => { setPlaying(reduxPlaying); }, [reduxPlaying]);

  useEffect(() => {
    if (!pipSupported) return;
    const video = videoElRef.current;
    if (!video) return;
    const onEnter = () => dispatch(setPiP(true));
    const onLeave = () => dispatch(setPiP(false));
    video.addEventListener("enterpictureinpicture", onEnter);
    video.addEventListener("leavepictureinpicture", onLeave);
    return () => {
      video.removeEventListener("enterpictureinpicture", onEnter);
      video.removeEventListener("leavepictureinpicture", onLeave);
    };
  }, [pipSupported, dispatch]);

  useEffect(() => {
    return () => {
      const video = videoElRef.current;
      if (video && isFinite(video.currentTime) && video.currentTime > 0) {
        dispatch(setCurrentTime(video.currentTime));
      }
      if (document.pictureInPictureElement) document.exitPictureInPicture().catch(() => {});
      dispatch(setPiP(false));
    };
  }, [dispatch]);

  const handleReady = () => {
    if (playerRef.current) {
      const internal = playerRef.current.getInternalPlayer?.();
      if (internal instanceof HTMLVideoElement) {
        videoElRef.current = internal;
        if (typeof document !== "undefined" && document.pictureInPictureEnabled) setPipSup(true);
      }
    }
    if (!didSeekRef.current && resumeTime > 1) {
      if (videoElRef.current) videoElRef.current.currentTime = resumeTime;
      else playerRef.current?.seekTo(resumeTime, "seconds");
    }
    didSeekRef.current = true;
  };

  const handlePiPToggle = async () => {
    const video = videoElRef.current;
    if (!video) return;
    try {
      if (!document.pictureInPictureElement) await video.requestPictureInPicture();
      else await document.exitPictureInPicture();
    } catch { /* blocked */ }
  };

  return (
    <div
      className="relative w-full rounded-xl overflow-hidden group"
      style={{ aspectRatio: "16/9", background: "var(--deep)" }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <ReactPlayer
        ref={playerRef}
        src={url}
        playing={playing}
        volume={volume / 100}
        width="100%"
        height="100%"
        controls
        onReady={handleReady}
        onPlay={() => { setPlaying(true);  if (!reduxPlaying) dispatch(togglePlay()); }}
        onPause={() => { setPlaying(false); if (reduxPlaying)  dispatch(togglePlay()); }}
        onBuffer={() => setBuffering(true)}
        onBufferEnd={() => setBuffering(false)}
        onProgress={(s: { playedSeconds: number }) => dispatch(setCurrentTime(s.playedSeconds))}
        onDuration={(dur: number) => dispatch(setDuration(Math.floor(dur)))}
        style={{ position: "absolute", inset: 0 }}
        config={{ youtube: { playerVars: { rel: 0, modestbranding: 1, iv_load_policy: 3 } } }}
      />

      {buffering && (
        <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
          <div
            className="w-10 h-10 rounded-full border-2 animate-spin"
            style={{ borderColor: "rgba(var(--accent-rgb),0.3)", borderTopColor: "var(--accent)" }}
          />
        </div>
      )}

      {pipSupported && (
        <div
          className="absolute top-3 right-3 z-10 transition-all duration-200"
          style={{ opacity: hovered || isPiP ? 1 : 0, pointerEvents: hovered || isPiP ? "auto" : "none" }}
        >
          <PiPButton isActive={isPiP} onClick={handlePiPToggle} />
        </div>
      )}
    </div>
  );
}

/* ── Public entry point — routes to YouTube or custom player ─────────────── */
export function VideoPlayer({ url, contentUploadType }: VideoPlayerProps) {
  if (contentUploadType === "youtube") {
    return <YouTubePlayer url={url} />;
  }
  return <CustomVideoPlayer url={url} />;
}

/* ── Skeleton ─────────────────────────────────────────────────────────────── */
export function VideoPlayerSkeleton() {
  return (
    <div
      className="w-full rounded-xl overflow-hidden animate-pulse"
      style={{ aspectRatio: "16/9", background: "var(--deep)", position: "relative" }}
    >
      <div className="absolute inset-0 flex items-center justify-center">
        <div
          className="w-14 h-14 rounded-full flex items-center justify-center"
          style={{ background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.08)" }}
        >
          <svg width="22" height="22" viewBox="0 0 24 24" fill="rgba(255,255,255,0.15)">
            <path d="M8 5v14l11-7z" />
          </svg>
        </div>
      </div>
      <div
        className="absolute bottom-0 left-0 right-0 h-10 px-4 flex items-center gap-3"
        style={{ background: "rgba(0,0,0,0.4)" }}
      >
        <div className="h-1 flex-1 rounded-full" style={{ background: "rgba(255,255,255,0.08)" }} />
        <div className="h-2.5 w-12 rounded-full" style={{ background: "rgba(255,255,255,0.08)" }} />
      </div>
    </div>
  );
}
