import React, { useState, useRef, useEffect, KeyboardEvent } from 'react';

interface CommandInputProps {
  onSubmit: (command: string) => void;
  isProcessing: boolean;
  getPreviousCommand: () => string | null;
  getNextCommand: () => string | null;
  resetCommandIndex: () => void;
  placeholder?: string;
}

export const CommandInput: React.FC<CommandInputProps> = ({
  onSubmit,
  isProcessing,
  getPreviousCommand,
  getNextCommand,
  resetCommandIndex,
  placeholder = 'Type command or natural language query...'
}) => {
  const [input, setInput] = useState('');
  const [showSuggestions, setShowSuggestions] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const suggestionsRef = useRef<HTMLDivElement>(null);

  const suggestions = [
    { command: '/search', description: 'Search live security data' },
    { command: '/portfolio', description: 'Show portfolio' },
    { command: '/news', description: 'Market news' },
    { command: '/analyze', description: 'AI analysis' },
    { command: '/help', description: 'List commands' }
  ];

  useEffect(() => {
    if (!isProcessing) {
      inputRef.current?.focus();
    }
  }, [isProcessing]);

  const handleSubmit = () => {
    const trimmed = input.trim();
    if (trimmed && !isProcessing) {
      onSubmit(trimmed);
      setInput('');
      setShowSuggestions(false);
      resetCommandIndex();
    }
  };

  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSubmit();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      const prev = getPreviousCommand();
      if (prev !== null) {
        setInput(prev);
      }
    } else if (e.key === 'ArrowDown') {
      e.preventDefault();
      const next = getNextCommand();
      if (next !== null) {
        setInput(next);
      }
    } else if (e.key === 'Tab') {
      e.preventDefault();
      // Simple autocomplete
      if (input.startsWith('/')) {
        const match = suggestions.find(s => s.command.startsWith(input));
        if (match) {
          setInput(match.command + ' ');
        }
      }
    } else if (e.key === 'Escape') {
      setShowSuggestions(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInput(e.target.value);
    if (e.target.value.startsWith('/')) {
      setShowSuggestions(true);
    } else {
      setShowSuggestions(false);
    }
  };

  const handleSuggestionClick = (command: string) => {
    setInput(command + ' ');
    setShowSuggestions(false);
    inputRef.current?.focus();
  };

  return (
    <div className="relative">
      {/* Suggestions Dropdown */}
      {showSuggestions && suggestions.some(s => s.command.startsWith(input)) && (
        <div
          ref={suggestionsRef}
          className="absolute top-full left-0 right-0 mt-2 bg-[#1a1a1a] border border-[#2a2a2a] rounded-md overflow-hidden shadow-lg z-20"
        >
          {suggestions
            .filter(s => !input || s.command.startsWith(input))
            .map((suggestion, idx) => (
              <button
                key={idx}
                className="w-full text-left px-4 py-2 hover:bg-[#2a2a2a] transition-colors font-mono text-sm"
                onClick={() => handleSuggestionClick(suggestion.command)}
              >
                <span className="text-[#58a6ff]">{suggestion.command}</span>
                <span className="text-[#888888] ml-2">{suggestion.description}</span>
              </button>
            ))}
        </div>
      )}

      {/* Input Bar */}
      <div className="flex items-center gap-2 bg-[#1a1a1a] border border-[#2a2a2a] rounded-md px-4 py-3 focus-within:border-[#58a6ff] focus-within:shadow-[0_0_0_2px_rgba(88,166,255,0.1)] transition-all">
        {/* Prompt */}
        <span className="text-[#58a6ff] font-mono text-lg select-none">{'>'}</span>

        {/* Input */}
        <input
          ref={inputRef}
          type="text"
          value={input}
          onChange={handleInputChange}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
          disabled={isProcessing}
          className="flex-1 bg-transparent border-none outline-none text-[#e0e0e0] font-mono text-[15px] placeholder-[#888888] disabled:opacity-50"
        />

        {/* Processing Indicator */}
        {isProcessing && (
          <div className="flex items-center gap-1">
            <span className="w-2 h-2 bg-[#58a6ff] rounded-full animate-pulse"></span>
            <span className="w-2 h-2 bg-[#58a6ff] rounded-full animate-pulse delay-75"></span>
            <span className="w-2 h-2 bg-[#58a6ff] rounded-full animate-pulse delay-150"></span>
          </div>
        )}

        {/* Submit Hint */}
        {!isProcessing && input && (
          <span className="text-[#888888] text-xs font-mono select-none">↵</span>
        )}
      </div>

      {/* Command hint */}
      <div className="mt-2 flex gap-4 text-xs text-[#888888] font-mono">
        <span>↑/↓ history</span>
        <span>Tab autocomplete</span>
        <span>Ctrl+L clear</span>
      </div>
    </div>
  );
};
