import {useEffect, useState} from 'react';

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

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

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