import { useEffect, useState } from "react";
import { useMediaSettingsStore } from "@/stores/media-settings-store";

interface UseStreamKeyboardNavOptions {
  streams: Array<{ id: string }>;
  enabled: boolean;
  onNavigate: (streamId: string) => void;
}

export function useStreamKeyboardNav({
  streams,
  enabled,
  onNavigate,
}: UseStreamKeyboardNavOptions) {
  const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
  const recordingMode = useMediaSettingsStore((s) => s.recordingMode);
  const setRecordingMode = useMediaSettingsStore((s) => s.setRecordingMode);

  // Initialize selection when streams first load; clear if streams become empty.
  // Do NOT reset on every Firestore update — that would scroll the list to the top.
  useEffect(() => {
    setSelectedIndex((prev) => {
      if (streams.length === 0) return null;
      if (prev === null) return 0;
      return prev;
    });
  }, [streams.length]);

  useEffect(() => {
    if (!enabled || streams.length === 0) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.defaultPrevented) return;

      const target = e.target as HTMLElement;
      if (
        target.tagName === "INPUT" ||
        target.tagName === "TEXTAREA" ||
        target.isContentEditable
      ) {
        return;
      }

      // Number keys 1-9: immediate navigation
      const digit = parseInt(e.key, 10);
      if (digit >= 1 && digit <= 9) {
        const index = digit - 1;
        if (index < streams.length) {
          e.preventDefault();
          onNavigate(streams[index].id);
        }
        return;
      }

      // Enter: navigate to selected
      if (e.key === "Enter") {
        setSelectedIndex((idx) => {
          if (idx !== null && idx < streams.length) {
            e.preventDefault();
            onNavigate(streams[idx].id);
          }
          return idx;
        });
        return;
      }

      // V: toggle video / audio
      if (e.key === "v" || e.key === "V") {
        e.preventDefault();
        setRecordingMode(recordingMode === "video" ? "audio" : "video");
        return;
      }

      // Arrow keys: move selection
      let delta: number | null = null;

      if (e.key === "ArrowDown") delta = 1;
      else if (e.key === "ArrowUp") delta = -1;

      if (delta !== null) {
        e.preventDefault();
        setSelectedIndex((prev) => {
          if (prev === null) return 0;
          const next = prev + delta;
          return Math.max(0, Math.min(next, streams.length - 1));
        });
      }
    };

    // Use capture phase so arrow keys are intercepted before Radix UI
    // components (ToggleGroup, etc.) consume them for their own navigation.
    window.addEventListener("keydown", handleKeyDown, true);
    return () => window.removeEventListener("keydown", handleKeyDown, true);
  }, [enabled, streams, onNavigate, recordingMode, setRecordingMode]);

  return { selectedIndex };
}
