import {useEffect, useState} from 'react';

import {useClient} from '@/react/context/client.js';

import styles from './input.module.css';

export default function ChatInput({
  setChatHistoryCaret,
  chatHistory,
  chatHistoryCaret,
  chatInputRef,
  message,
  pendingMessage,
  setChatHistory,
  setMessage,
  setPendingMessage,
}) {
  const client = useClient();
  const [disabled, setDisabled] = useState(true);
  useEffect(() => {
    setDisabled(false);
  }, []);
  return (
    <form
      className={styles.input}
      onSubmit={(event) => {
        if (message) {
          client.send({
            type: 'Action',
            payload: {type: 'chat', value: message},
          });
          setChatHistory([message, ...chatHistory]);
          setChatHistoryCaret(-1);
          setPendingMessage('');
          setMessage('');
        }
        event.preventDefault();
      }}
    >
      <input
        disabled={disabled}
        onChange={(event) => {
          setMessage(event.target.value);
        }}
        onKeyDown={(event) => {
          switch (event.key) {
            case 'ArrowDown': {
              if (-1 === chatHistoryCaret) {
                break;
              }
              else if (0 === chatHistoryCaret) {
                setMessage(pendingMessage);
                setPendingMessage('');
              }
              else {
                setMessage(chatHistory[chatHistoryCaret - 1])
              }
              setChatHistoryCaret(chatHistoryCaret - 1);
              break;
            }
            case 'ArrowUp': {
              if (chatHistory.length - 1 === chatHistoryCaret) {
                break;
              }
              if (-1 === chatHistoryCaret) {
                setPendingMessage(message);
              }
              setMessage(chatHistory[chatHistoryCaret + 1])
              setChatHistoryCaret(chatHistoryCaret + 1);
              break;
            }
          }
        }}
        onMouseDown={(event) => {
          event.stopPropagation();
        }}
        maxLength="255"
        ref={(element) => {
          chatInputRef.current = element;
          if (element) {
            element.focus();
          }
        }}
        type="text"
        value={message}
      />
    </form>
  );
}