import { useState, useCallback } from 'react';

const MAX_HISTORY = 50;

export function useInputHistory() {
  const [history, setHistory] = useState<string[]>([]);
  const [historyIndex, setHistoryIndex] = useState<number>(-1);
  const [savedInput, setSavedInput] = useState<string>('');

  const addToHistory = useCallback((input: string) => {
    if (!input.trim()) return;
    setHistory((prev) => {
      // Avoid duplicate consecutive entries
      if (prev[0] === input) return prev;
      return [input, ...prev].slice(0, MAX_HISTORY);
    });
    setHistoryIndex(-1);
  }, []);

  const navigateUp = useCallback(
    (currentInput: string): string | null => {
      if (history.length === 0) return null;
      if (historyIndex === -1) {
        setSavedInput(currentInput);
      }
      const nextIndex = Math.min(historyIndex + 1, history.length - 1);
      setHistoryIndex(nextIndex);
      return history[nextIndex] ?? null;
    },
    [history, historyIndex],
  );

  const navigateDown = useCallback((): string | null => {
    if (historyIndex <= 0) {
      setHistoryIndex(-1);
      return savedInput;
    }
    const nextIndex = historyIndex - 1;
    setHistoryIndex(nextIndex);
    return history[nextIndex] ?? null;
  }, [history, historyIndex, savedInput]);

  const resetNavigation = useCallback(() => {
    setHistoryIndex(-1);
  }, []);

  return { addToHistory, navigateUp, navigateDown, resetNavigation };
}
