import { useCallback, useEffect } from "react";
import type { MediaSyncState } from "../hooks/useMediaSync";

interface PlayerControlsProps {
  mediaSync: MediaSyncState;
  /** Ref to the container element for fullscreen requests */
  containerRef?: React.RefObject<HTMLElement | null>;
}

const SPEED_OPTIONS = [0.5, 0.75, 1, 1.25, 1.5, 2] as const;

function formatTime(seconds: number): string {
  if (!Number.isFinite(seconds) || seconds < 0) return "0:00";
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m}:${s.toString().padStart(2, "0")}`;
}

export default function PlayerControls({ mediaSync, containerRef }: PlayerControlsProps) {
  const {
    currentTime,
    duration,
    isPlaying,
    playbackRate,
    volume,
    isMuted,
    seekTo,
    setPlaybackRate,
    togglePlay,
    setVolume,
    toggleMute,
  } = mediaSync;

  const seekDisabled = !duration || duration === 0;

  const handleSeek = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      seekTo(parseFloat(e.target.value));
    },
    [seekTo],
  );

  const handleVolume = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      setVolume(parseFloat(e.target.value));
    },
    [setVolume],
  );

  const handleFullscreen = useCallback(() => {
    const el = containerRef?.current;
    if (!el) return;
    if (document.fullscreenElement) {
      void document.exitFullscreen();
    } else {
      void el.requestFullscreen();
    }
  }, [containerRef]);

  // Keyboard shortcuts
  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      // Don't intercept when typing in inputs
      const tag = (e.target as HTMLElement)?.tagName;
      if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;

      switch (e.key) {
        case " ":
          e.preventDefault();
          togglePlay();
          break;
        case "ArrowLeft":
          e.preventDefault();
          seekTo(Math.max(0, currentTime - 5));
          break;
        case "ArrowRight":
          e.preventDefault();
          seekTo(Math.min(duration, currentTime + 5));
          break;
        case "ArrowUp":
          e.preventDefault();
          setVolume(Math.min(1, volume + 0.1));
          break;
        case "ArrowDown":
          e.preventDefault();
          setVolume(Math.max(0, volume - 0.1));
          break;
      }
    };

    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [togglePlay, seekTo, setVolume, currentTime, duration, volume]);

  // Seek bar progress as CSS variable for styling
  const seekProgress = duration > 0 ? (currentTime / duration) * 100 : 0;
  const volumeProgress = (isMuted ? 0 : volume) * 100;

  return (
    <div className="player-controls" role="toolbar" aria-label="Video playback controls">
      {/* Play/Pause */}
      <button
        className="player-controls__btn"
        onClick={togglePlay}
        aria-label={isPlaying ? "Pause" : "Play"}
        title={isPlaying ? "Pause" : "Play"}
      >
        {isPlaying ? (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
            <path d="M6 4h4v16H6zM14 4h4v16h-4z" />
          </svg>
        ) : (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
            <path d="M8 5v14l11-7z" />
          </svg>
        )}
      </button>

      {/* Time display */}
      <span className="player-controls__time">
        {formatTime(currentTime)} / {formatTime(duration)}
      </span>

      {/* Seek bar */}
      <input
        type="range"
        className="player-controls__seek"
        min={0}
        max={duration || 0}
        step={0.1}
        value={currentTime}
        onChange={handleSeek}
        disabled={seekDisabled}
        aria-label="Seek"
        style={{ "--progress": `${seekProgress}%` } as React.CSSProperties}
      />

      {/* Speed selector */}
      <div className="player-controls__speed" role="group" aria-label="Playback speed">
        {SPEED_OPTIONS.map((rate) => (
          <button
            key={rate}
            className={`player-controls__speed-btn${playbackRate === rate ? " player-controls__speed-btn--active" : ""}`}
            onClick={() => setPlaybackRate(rate)}
            aria-pressed={playbackRate === rate}
          >
            {rate}x
          </button>
        ))}
      </div>

      {/* Volume */}
      <button
        className="player-controls__btn"
        onClick={toggleMute}
        aria-label={isMuted ? "Unmute" : "Mute"}
        title={isMuted ? "Unmute" : "Mute"}
      >
        {isMuted || volume === 0 ? (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
            <path d="M16.5 12A4.5 4.5 0 0014 8.14v1.44l2.45 2.45c.03-.17.05-.34.05-.53zm2.5 0c0 .94-.2 1.82-.54 2.64l1.52 1.52A8.91 8.91 0 0021 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06a8.99 8.99 0 003.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z" />
          </svg>
        ) : (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
            <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3A4.5 4.5 0 0014 8.14v7.72c1.48-.73 2.5-2.25 2.5-3.86zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z" />
          </svg>
        )}
      </button>

      <input
        type="range"
        className="player-controls__volume"
        min={0}
        max={1}
        step={0.05}
        value={isMuted ? 0 : volume}
        onChange={handleVolume}
        aria-label="Volume"
        style={{ "--progress": `${volumeProgress}%` } as React.CSSProperties}
      />

      {/* Fullscreen */}
      <button
        className="player-controls__btn"
        onClick={handleFullscreen}
        aria-label="Fullscreen"
        title="Fullscreen"
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
          <path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z" />
        </svg>
      </button>
    </div>
  );
}
