import { useState, useCallback, useRef, useEffect } from 'react';
import { TerminalEntry, TerminalState } from '../types/terminal';

// Helper to create an entry with timestamp (exported for use in App.tsx)
export const createEntry = (
  entry: Omit<TerminalEntry, 'id' | 'timestamp'>
): TerminalEntry => ({
  ...entry,
  id: `${Date.now()}-${Math.random()}`,
  timestamp: new Date()
});

export const useTerminal = () => {
  const [state, setState] = useState<TerminalState>({
    history: [
      {
        id: 'welcome',
        type: 'system',
        content: 'MosaicIQ Financial Terminal v1.0\nType /help for available commands or try a natural language query.',
        timestamp: new Date()
      }
    ],
    currentIndex: -1,
    isProcessing: false
  });

  const commandHistoryRef = useRef<string[]>([]);
  const outputRef = useRef<HTMLDivElement>(null);

  // Auto-scroll to bottom when new entries are added
  useEffect(() => {
    if (outputRef.current) {
      outputRef.current.scrollTop = outputRef.current.scrollHeight;
    }
  }, [state.history]);

  const addEntry = useCallback((entry: Omit<TerminalEntry, 'id' | 'timestamp'>) => {
    const newEntry: TerminalEntry = createEntry(entry);

    setState(prev => ({
      ...prev,
      history: [...prev.history, newEntry]
    }));

    return newEntry.id;
  }, []);

  const addCommand = useCallback((command: string) => {
    commandHistoryRef.current.push(command);
    const entry: TerminalEntry = createEntry({
      type: 'command',
      content: command
    });
    setState(prev => ({
      ...prev,
      history: [...prev.history, entry]
    }));
  }, []);

  const setProcessing = useCallback((isProcessing: boolean) => {
    setState(prev => ({ ...prev, isProcessing }));
  }, []);

  const clearTerminal = useCallback(() => {
    setState(prev => ({
      ...prev,
      history: []
    }));
  }, []);

  const getPreviousCommand = useCallback(() => {
    const history = commandHistoryRef.current;
    if (state.currentIndex < history.length - 1) {
      const newIndex = state.currentIndex + 1;
      setState(prev => ({ ...prev, currentIndex: newIndex }));
      return history[history.length - 1 - newIndex];
    }
    return null;
  }, [state.currentIndex]);

  const getNextCommand = useCallback(() => {
    if (state.currentIndex > 0) {
      const newIndex = state.currentIndex - 1;
      setState(prev => ({ ...prev, currentIndex: newIndex }));
      return commandHistoryRef.current[commandHistoryRef.current.length - 1 - newIndex];
    } else if (state.currentIndex === 0) {
      setState(prev => ({ ...prev, currentIndex: -1 }));
      return '';
    }
    return null;
  }, [state.currentIndex]);

  const resetCommandIndex = useCallback(() => {
    setState(prev => ({ ...prev, currentIndex: -1 }));
  }, []);

  return {
    state,
    outputRef,
    addEntry,
    addCommand,
    setProcessing,
    clearTerminal,
    getPreviousCommand,
    getNextCommand,
    resetCommandIndex
  };
};
