import React, { KeyboardEvent, useState } from 'react';
import styles from './ChatAssistant.module.css';

interface ChatInputProps {
  isSending: boolean;
  onSend: (text: string) => Promise<void>;
  inputRef?: React.RefObject<HTMLTextAreaElement | null>;
}

const ChatInput: React.FC<ChatInputProps> = ({ isSending, onSend, inputRef }) => {
  const [value, setValue] = useState('');

  const handleSend = async (): Promise<void> => {
    const text = value.trim();

    if (!text || isSending) {
      return;
    }

    setValue('');
    await onSend(text);
  };

  const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>): void => {
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault();
      void handleSend();
    }
  };

  return (
    <div className={styles.chatInputArea}>
      <textarea
        ref={inputRef}
        id="chat-assistant-input"
        className={styles.chatInput}
        rows={2}
        value={value}
        onChange={(event) => setValue(event.target.value)}
        onKeyDown={handleKeyDown}
        placeholder="Escribe tu consulta..."
        disabled={isSending}
        aria-label="Mensaje para el asistente"
      />
      <button
        type="button"
        id="chat-assistant-send"
        className={styles.chatSendButton}
        onClick={() => void handleSend()}
        disabled={isSending || value.trim().length === 0}
        aria-label="Enviar mensaje"
      >
        <i className="ri-send-plane-2-fill" aria-hidden="true" />
      </button>
    </div>
  );
};

export default ChatInput;
