/**
 * ChatInput Component
 * Expandable textarea for sending messages
 */

import React, { useState, useRef, useEffect, KeyboardEvent } from 'react';
import { Send, Loader2 } from 'lucide-react';

interface ChatInputProps {
  onSendMessage: (message: string) => void;
  disabled?: boolean;
  loading?: boolean;
  placeholder?: string;
}

export const ChatInput: React.FC<ChatInputProps> = ({
  onSendMessage,
  disabled = false,
  loading = false,
  placeholder = 'Ask me anything about trading...',
}) => {
  const [message, setMessage] = useState('');
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // Auto-resize textarea
  useEffect(() => {
    const textarea = textareaRef.current;
    if (textarea) {
      textarea.style.height = 'auto';
      textarea.style.height = `${Math.min(textarea.scrollHeight, 150)}px`;
    }
  }, [message]);

  // Focus on mount
  useEffect(() => {
    if (!disabled && !loading) {
      textareaRef.current?.focus();
    }
  }, [disabled, loading]);

  const handleSubmit = () => {
    const trimmedMessage = message.trim();
    if (!trimmedMessage || disabled || loading) return;

    onSendMessage(trimmedMessage);
    setMessage('');

    // Reset textarea height
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
    }
  };

  const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    // Submit on Enter (without Shift)
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit();
    }
  };

  const isDisabled = disabled || loading;

  return (
    <div className="border-t border-gray-700 bg-gray-900 p-4">
      <div className="flex gap-2 items-end">
        {/* Textarea */}
        <div className="flex-1 relative">
          <textarea
            ref={textareaRef}
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={placeholder}
            disabled={isDisabled}
            rows={1}
            className={`
              w-full
              px-4 py-3
              bg-gray-800
              border border-gray-700
              rounded-lg
              text-gray-100
              placeholder-gray-500
              focus:outline-none
              focus:ring-2
              focus:ring-blue-500
              focus:border-transparent
              resize-none
              transition-all
              ${isDisabled ? 'opacity-50 cursor-not-allowed' : ''}
            `}
            style={{
              minHeight: '44px',
              maxHeight: '150px',
            }}
          />

          {/* Character counter (optional, shown when approaching limit) */}
          {message.length > 1000 && (
            <div
              className={`
                absolute bottom-1 right-2
                text-xs
                ${message.length > 1500 ? 'text-red-400' : 'text-gray-500'}
              `}
            >
              {message.length}/2000
            </div>
          )}
        </div>

        {/* Send button */}
        <button
          onClick={handleSubmit}
          disabled={isDisabled || !message.trim()}
          className={`
            flex-shrink-0
            w-11 h-11
            flex items-center justify-center
            rounded-lg
            transition-all
            ${
              isDisabled || !message.trim()
                ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
                : 'bg-blue-600 text-white hover:bg-blue-700 active:scale-95'
            }
          `}
          title="Send message (Enter)"
        >
          {loading ? (
            <Loader2 className="w-5 h-5 animate-spin" />
          ) : (
            <Send className="w-5 h-5" />
          )}
        </button>
      </div>

      {/* Helper text */}
      <div className="mt-2 text-xs text-gray-500 text-center">
        Press <kbd className="px-1.5 py-0.5 bg-gray-800 rounded">Enter</kbd> to send,{' '}
        <kbd className="px-1.5 py-0.5 bg-gray-800 rounded">Shift</kbd> +{' '}
        <kbd className="px-1.5 py-0.5 bg-gray-800 rounded">Enter</kbd> for new line
      </div>
    </div>
  );
};

export default ChatInput;
