import { useEffect, useRef, useState, useCallback } from "react";
import {
  SkipBack,
  SkipForward,
  Play,
  Pause,
  Maximize2,
} from "lucide-react";
import VideoPlayer from "@/components/VideoPlayer";

/**
 * InlinePreviewPlayer — small preview wrapper around <VideoPlayer> used on
 * the Live TV page. Renders a compact player + a gold control bar:
 *
 *   ⏮ Previous channel │ ⏯ Play / Pause │ ⏭ Next channel │ ⛶ Fullscreen
 *
 * Fullscreen is also triggered by double-tapping the video. When in
 * fullscreen, the control bar overlays the bottom of the video.
 *
 * Play/pause is proxied to the <video> element rendered inside the
 * inner VideoPlayer via querySelector — the VideoPlayer owns the HLS
 * lifecycle so we must not fork it.
 *
 * Admin toggle: `inline_preview_enabled`. When false, LiveTV falls back
 * to rendering <VideoPlayer> directly (no wrapper, no controls).
 */
interface InlinePreviewPlayerProps {
  src: string;
  poster?: string;
  title?: string;
  isLive?: boolean;
  /** Called when user taps the prev-channel (⏮) icon. */
  onPrevChannel?: () => void;
  /** Called when user taps the next-channel (⏭) icon. */
  onNextChannel?: () => void;
  /** Whether the prev/next buttons should be enabled. */
  canGoPrev?: boolean;
  canGoNext?: boolean;
  liveScaleMode?: "contain" | "cover" | "fill";
}

const InlinePreviewPlayer = ({
  src,
  poster,
  title,
  isLive,
  onPrevChannel,
  onNextChannel,
  canGoPrev = true,
  canGoNext = true,
  liveScaleMode = "contain",
}: InlinePreviewPlayerProps) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [isPlaying, setIsPlaying] = useState<boolean>(false);
  const [isFullscreen, setIsFullscreen] = useState<boolean>(false);

  // ── Query the inner <video> element (owned by VideoPlayer) ──
  const getVideo = useCallback((): HTMLVideoElement | null => {
    return containerRef.current?.querySelector("video") ?? null;
  }, []);

  // Keep local isPlaying in sync with the actual <video> element state.
  useEffect(() => {
    const video = getVideo();
    if (!video) return;
    const onPlay = () => setIsPlaying(true);
    const onPause = () => setIsPlaying(false);
    video.addEventListener("play", onPlay);
    video.addEventListener("pause", onPause);
    // Seed with current state (video may already be auto-playing).
    setIsPlaying(!video.paused);
    return () => {
      video.removeEventListener("play", onPlay);
      video.removeEventListener("pause", onPause);
    };
  }, [getVideo, src]);

  // Listen for native fullscreenchange so our icon stays in sync when the
  // user hits ESC or the browser's own fullscreen exit button.
  useEffect(() => {
    const handler = () => {
      setIsFullscreen(document.fullscreenElement === containerRef.current);
    };
    document.addEventListener("fullscreenchange", handler);
    return () => document.removeEventListener("fullscreenchange", handler);
  }, []);

  // ── Controls ──────────────────────────────────────────────────────
  const togglePlay = useCallback(() => {
    const video = getVideo();
    if (!video) return;
    if (video.paused) {
      void video.play();
    } else {
      video.pause();
    }
  }, [getVideo]);

  const requestFullscreen = useCallback(() => {
    const el = containerRef.current;
    if (!el) return;
    if (document.fullscreenElement === el) {
      void document.exitFullscreen();
    } else if (el.requestFullscreen) {
      void el.requestFullscreen().catch(() => {
        /* browser denied (e.g. iOS Safari) — ignore */
      });
    }
  }, []);

  // Double-tap / double-click on the video → fullscreen.
  const handleDoubleTap = useCallback(
    (e: React.MouseEvent) => {
      e.preventDefault();
      requestFullscreen();
    },
    [requestFullscreen],
  );

  return (
    <div
      ref={containerRef}
      className="relative w-full h-full bg-black rounded-xl overflow-hidden flex flex-col"
      data-testid="inline-preview-player"
    >
      {/* Video area — inherits all HLS/autoplay/DRM logic from VideoPlayer */}
      <div
        className="relative flex-1 min-h-0"
        onDoubleClick={handleDoubleTap}
      >
        <VideoPlayer
          src={src}
          poster={poster}
          title={title}
          isLive={isLive}
          liveScaleMode={liveScaleMode}
        />
      </div>

      {/* Gold control bar — always visible below the video (or overlay in FS) */}
      <div
        className={[
          "flex items-center justify-center gap-1 px-3 py-2 bg-gradient-to-t from-black/90 via-black/70 to-transparent",
          isFullscreen
            ? "absolute bottom-0 left-0 right-0 z-20 pointer-events-auto"
            : "relative",
        ].join(" ")}
        data-testid="inline-preview-controls"
      >
        <ControlButton
          label="Previous channel"
          testId="inline-prev-channel"
          disabled={!canGoPrev || !onPrevChannel}
          onClick={() => onPrevChannel?.()}
        >
          <SkipBack className="w-5 h-5" fill="currentColor" strokeWidth={0} />
        </ControlButton>

        <ControlButton
          label={isPlaying ? "Pause" : "Play"}
          testId="inline-play-pause"
          onClick={togglePlay}
        >
          {isPlaying ? (
            <Pause className="w-6 h-6" fill="currentColor" strokeWidth={0} />
          ) : (
            <Play className="w-6 h-6 ml-0.5" fill="currentColor" strokeWidth={0} />
          )}
        </ControlButton>

        <ControlButton
          label="Next channel"
          testId="inline-next-channel"
          disabled={!canGoNext || !onNextChannel}
          onClick={() => onNextChannel?.()}
        >
          <SkipForward className="w-5 h-5" fill="currentColor" strokeWidth={0} />
        </ControlButton>

        <ControlButton
          label={isFullscreen ? "Exit fullscreen" : "Fullscreen"}
          testId="inline-fullscreen"
          onClick={requestFullscreen}
        >
          <Maximize2 className="w-5 h-5" strokeWidth={2.5} />
        </ControlButton>
      </div>
    </div>
  );
};

// ── Internal control button (gold icon, large tap target) ──────────────
interface ControlButtonProps {
  label: string;
  testId: string;
  onClick: () => void;
  disabled?: boolean;
  children: React.ReactNode;
}

const ControlButton = ({
  label,
  testId,
  onClick,
  disabled,
  children,
}: ControlButtonProps) => (
  <button
    type="button"
    onClick={onClick}
    disabled={disabled}
    aria-label={label}
    title={label}
    data-testid={testId}
    className={[
      "min-w-[48px] min-h-[48px] flex items-center justify-center",
      "rounded-full transition-all duration-150",
      "text-primary hover:bg-primary/15 active:scale-95",
      "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",
      disabled ? "opacity-30 cursor-not-allowed" : "cursor-pointer",
    ].join(" ")}
  >
    {children}
  </button>
);

export default InlinePreviewPlayer;
