import type { RefObject } from "react";
import { useEffect } from "react";

interface UseKeyboardControlsOptions {
	onSeek?: (delta: number) => void;
	onVolumeChange?: (delta: number) => void;
}

export function useKeyboardControls(
	videoRef: RefObject<HTMLVideoElement | null>,
	options: UseKeyboardControlsOptions = {},
) {
	useEffect(() => {
		const handleKeyPress = (e: KeyboardEvent) => {
			if (!videoRef.current) return;

			// Ignore if typing in input field
			const target = e.target as HTMLElement;
			if (
				target.tagName === "INPUT" ||
				target.tagName === "TEXTAREA" ||
				target.isContentEditable
			) {
				return;
			}

			const video = videoRef.current;

			switch (e.key) {
				case " ":
				case "k":
					e.preventDefault();
					if (video.paused) {
						video.play();
					} else {
						video.pause();
					}
					break;

				case "ArrowLeft":
					e.preventDefault();
					if (options.onSeek) {
						options.onSeek(-10);
					} else {
						video.currentTime = Math.max(0, video.currentTime - 10);
					}
					break;

				case "ArrowRight":
					e.preventDefault();
					if (options.onSeek) {
						options.onSeek(10);
					} else {
						video.currentTime = Math.min(
							video.duration,
							video.currentTime + 10,
						);
					}
					break;

				case "j":
					e.preventDefault();
					if (options.onSeek) {
						options.onSeek(-10);
					} else {
						video.currentTime = Math.max(0, video.currentTime - 10);
					}
					break;

				case "l":
					e.preventDefault();
					if (options.onSeek) {
						options.onSeek(10);
					} else {
						video.currentTime = Math.min(
							video.duration,
							video.currentTime + 10,
						);
					}
					break;

				case "f":
					e.preventDefault();
					if (document.fullscreenElement) {
						document.exitFullscreen();
					} else {
						video.requestFullscreen();
					}
					break;

				case "m":
					e.preventDefault();
					video.muted = !video.muted;
					break;

				case "ArrowUp":
					e.preventDefault();
					if (options.onVolumeChange) {
						options.onVolumeChange(0.1);
					} else {
						video.volume = Math.min(1, video.volume + 0.1);
					}
					break;

				case "ArrowDown":
					e.preventDefault();
					if (options.onVolumeChange) {
						options.onVolumeChange(-0.1);
					} else {
						video.volume = Math.max(0, video.volume - 0.1);
					}
					break;
			}
		};

		window.addEventListener("keydown", handleKeyPress);
		return () => window.removeEventListener("keydown", handleKeyPress);
	}, [videoRef, options]);
}
