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

const TerminalApp = () => {
  const [currentTaskState, setTaskState] = useState(false);
  const [is_updated_libraries_state, set_updated_libraries_state] = useState(false);

  const [input, setInput] = useState('');
  const [history, setHistory] = useState([
    { type: 'system', text: 'Добро пожаловать в мини-терминал. Введите "help" для списка команд.' }
  ]);
  const bottomRef = useRef<HTMLDivElement>(null);

  // Автопрокрутка вниз при новых сообщениях
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [history]);

  const commands = {
    help: () => 'Доступные команды: help, clear, apt',

    "apt": () => "apt is package manager. Use 'apt help' for more info",
    "apt help": () => "apt avalible commands: apt update; apt upgrade;",
    "apt update": () => {
        set_updated_libraries_state(true);
        return "Yup, package list update, you can update system"
    },
    "apt upgrade": () => {
        if(is_updated_libraries_state) {
            setTaskState(true) // mark as done
            alert("Done!")
        }
        return "Yup, system and libraries updated for latest version"
    },
    
    clear: () => {
      setHistory([]);
      return null;
    }
  };

  const handleCommand = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      const cleanInput = input.trim().toLowerCase();
      const newHistory = [...history, { type: 'user', text: `> ${input}` }];

      if (cleanInput) {
        if (cleanInput in commands) {
          const result = commands[cleanInput as keyof typeof commands]();
          if (result){
            newHistory.push({ type: 'bot', text: result });
            setHistory(newHistory);
          }
        } else {
          newHistory.push({ type: 'error', text: `Команда "${cleanInput}" не найдена. Введите "help".` });
          setHistory(newHistory);
        }
      }

      setInput('');
    }
  };

  return (
    <div style={styles.container}>
      <div style={styles.terminal}>
        {history.map((line, i) => (
          <div key={i} style={{ ...styles.line, ...styles[line.type as keyof typeof styles] }}>
            {line.text}
          </div>
        ))}
        <div ref={bottomRef} />
      </div>
      <div style={styles.inputLine}>
        <span style={styles.prompt}>$</span>
        <input
          style={styles.input}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={handleCommand}
          autoFocus
        />
      </div>
        {currentTaskState}
    </div>
  );
};

const styles = {
  container: { backgroundColor: '#1e1e1e', color: '#00ff00', padding: '20px', fontFamily: 'monospace', height: '400px', display: 'flex', flexDirection: 'column' as const, borderRadius: '8px' },
  terminal: { flex: 1, overflowY: 'auto' as const, marginBottom: '10px' },
  line: { marginBottom: '4px', whiteSpace: 'pre-wrap' as const, textAlign: 'justify' as const },
  user: { color: '#fff' },
  error: { color: '#ff5555' },
  system: { color: '#aaa' },
  inputLine: { display: 'flex', alignItems: 'center' },
  prompt: { marginRight: '8px', fontWeight: 'bold' },
  input: { background: 'transparent', border: 'none', color: '#00ff00', outline: 'none', flex: 1, fontFamily: 'monospace', fontSize: '16px' }
};

export default TerminalApp;
