import { useState, useEffect, useRef, useCallback } from 'react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Input } from '@/components/ui/input';
import { executeCommand, CLIContext, CLIResult } from '@/lib/cli-commands';
import { toast } from 'sonner';

interface TerminalLine {
  id: string;
  type: 'input' | 'output' | 'error' | 'info' | 'warn' | 'log';
  content: string;
  timestamp: Date;
}

interface InteractiveTerminalProps {
  currentCode: string;
  currentFile?: string;
  files: any[];
  onCodeChange?: (code: string) => void;
}

export function InteractiveTerminal({
  currentCode,
  currentFile,
  files,
  onCodeChange,
}: InteractiveTerminalProps) {
  const [lines, setLines] = useState<TerminalLine[]>([
    {
      id: '0',
      type: 'info',
      content: 'AeThex Studio Terminal v1.0.0\nType "help" for available commands',
      timestamp: new Date(),
    },
  ]);
  const [input, setInput] = useState('');
  const [history, setHistory] = useState<string[]>([]);
  const [historyIndex, setHistoryIndex] = useState(-1);
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const inputRef = useRef<HTMLInputElement>(null);
  const scrollRef = useRef<HTMLDivElement>(null);

  // Auto-scroll to bottom
  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [lines]);

  // Focus input on mount
  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  const addLog = useCallback((message: string, type: TerminalLine['type'] = 'log') => {
    setLines(prev => [
      ...prev,
      {
        id: Date.now().toString(),
        type,
        content: message,
        timestamp: new Date(),
      },
    ]);
  }, []);

  const handleCommand = useCallback(async (command: string) => {
    if (!command.trim()) return;

    // Add command to history
    setHistory(prev => [...prev, command]);
    setHistoryIndex(-1);

    // Add input line
    addLog(`$ ${command}`, 'input');

    // Execute command
    const context: CLIContext = {
      currentCode,
      currentFile,
      files,
      setCode: onCodeChange,
      addLog,
    };

    try {
      const result: CLIResult = await executeCommand(command, context);

      // Handle special commands
      if (result.output === '__CLEAR__') {
        setLines([]);
        return;
      }

      // Add output
      if (result.output) {
        addLog(result.output, result.type || 'log');
      }

      if (!result.success && result.type !== 'warn') {
        toast.error(result.output);
      }
    } catch (error) {
      addLog(`Error: ${error}`, 'error');
      toast.error('Command execution failed');
    }
  }, [currentCode, currentFile, files, onCodeChange, addLog]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (input.trim()) {
      handleCommand(input);
      setInput('');
      setSuggestions([]);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // Command history navigation
    if (e.key === 'ArrowUp') {
      e.preventDefault();
      if (history.length > 0) {
        const newIndex = historyIndex === -1 ? history.length - 1 : Math.max(0, historyIndex - 1);
        setHistoryIndex(newIndex);
        setInput(history[newIndex]);
      }
    } else if (e.key === 'ArrowDown') {
      e.preventDefault();
      if (historyIndex !== -1) {
        const newIndex = historyIndex + 1;
        if (newIndex >= history.length) {
          setHistoryIndex(-1);
          setInput('');
        } else {
          setHistoryIndex(newIndex);
          setInput(history[newIndex]);
        }
      }
    } else if (e.key === 'Tab') {
      e.preventDefault();
      // Auto-complete
      if (suggestions.length > 0) {
        setInput(suggestions[0]);
        setSuggestions([]);
      }
    } else if (e.key === 'Escape') {
      setSuggestions([]);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setInput(value);

    // Simple auto-complete
    if (value.trim()) {
      const commandNames = [
        'help', 'clear', 'cls', 'run', 'execute', 'check', 'lint',
        'count', 'api', 'template', 'export', 'echo', 'info',
      ];
      const matches = commandNames.filter(cmd =>
        cmd.startsWith(value.toLowerCase())
      );
      setSuggestions(matches);
    } else {
      setSuggestions([]);
    }
  };

  const getLineColor = (type: TerminalLine['type']) => {
    switch (type) {
      case 'input':
        return 'text-accent font-semibold';
      case 'error':
        return 'text-red-400';
      case 'warn':
        return 'text-yellow-400';
      case 'info':
        return 'text-blue-400';
      case 'log':
        return 'text-green-400';
      default:
        return 'text-foreground';
    }
  };

  return (
    <div className="h-full flex flex-col bg-background/50 font-mono">
      <ScrollArea className="flex-1 px-4 py-2">
        <div className="space-y-1 text-xs">
          {lines.map((line) => (
            <div key={line.id} className={`whitespace-pre-wrap ${getLineColor(line.type)}`}>
              {line.content}
            </div>
          ))}
          <div ref={scrollRef} />
        </div>
      </ScrollArea>

      <div className="border-t border-border p-2">
        <form onSubmit={handleSubmit} className="relative">
          <div className="flex items-center gap-2">
            <span className="text-accent font-semibold text-sm">$</span>
            <Input
              ref={inputRef}
              type="text"
              value={input}
              onChange={handleInputChange}
              onKeyDown={handleKeyDown}
              className="flex-1 bg-background/50 border-none focus-visible:ring-1 focus-visible:ring-accent font-mono text-xs h-7 px-2"
              placeholder="Type a command... (try 'help')"
              spellCheck={false}
              autoComplete="off"
              aria-label="Terminal command input"
            />
          </div>

          {suggestions.length > 0 && (
            <div className="absolute bottom-full left-8 mb-1 bg-card border border-border rounded-md shadow-lg p-1 z-10">
              {suggestions.slice(0, 5).map((suggestion, index) => (
                <div
                  key={index}
                  className="px-2 py-1 text-xs hover:bg-accent/10 cursor-pointer rounded"
                  onClick={() => {
                    setInput(suggestion);
                    setSuggestions([]);
                    inputRef.current?.focus();
                  }}
                >
                  {suggestion}
                </div>
              ))}
            </div>
          )}
        </form>

        <div className="text-[10px] text-muted-foreground mt-1 flex items-center justify-between">
          <span>↑↓ History | Tab Complete | Esc Clear</span>
          <span>{history.length} commands</span>
        </div>
      </div>
    </div>
  );
}
