import React, { useState, useRef, useEffect } from 'react';
import { PaperAirplaneIcon, StopIcon } from '@heroicons/react/24/solid';
import { MicrophoneIcon, PaperClipIcon } from '@heroicons/react/24/outline';

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

export const ChatInput: React.FC<ChatInputProps> = ({
  onSendMessage,
  onStopStreaming,
  isLoading = false,
  isStreaming = false,
  placeholder = 'Ask about trading, signals, or market analysis...',
  disabled = false,
}) => {
  const [message, setMessage] = useState('');
  const textareaRef = useRef<HTMLTextAreaElement>(null);

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (message.trim() && !isLoading && !disabled) {
      onSendMessage(message.trim());
      setMessage('');
      if (textareaRef.current) {
        textareaRef.current.style.height = 'auto';
      }
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit(e);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="relative">
      <div className="flex items-end gap-2 p-3 bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700">
        {/* Attachment button */}
        <button
          type="button"
          className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
          title="Attach file"
        >
          <PaperClipIcon className="w-5 h-5" />
        </button>

        {/* Input area */}
        <div className="flex-1 relative">
          <textarea
            ref={textareaRef}
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={placeholder}
            disabled={disabled || isLoading}
            rows={1}
            className="w-full px-4 py-3 pr-12 bg-gray-100 dark:bg-gray-800 border-0 rounded-2xl resize-none focus:ring-2 focus:ring-primary-500 focus:outline-none text-gray-900 dark:text-white placeholder-gray-500 disabled:opacity-50"
          />
        </div>

        {/* Voice input button */}
        <button
          type="button"
          className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
          title="Voice input"
        >
          <MicrophoneIcon className="w-5 h-5" />
        </button>

        {/* Send/Stop button */}
        {isStreaming ? (
          <button
            type="button"
            onClick={onStopStreaming}
            className="p-3 bg-red-600 hover:bg-red-700 text-white rounded-xl transition-colors"
            title="Stop generating"
          >
            <StopIcon className="w-5 h-5" />
          </button>
        ) : (
          <button
            type="submit"
            disabled={!message.trim() || isLoading || disabled}
            className="p-3 bg-primary-600 hover:bg-primary-700 text-white rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            title="Send message"
          >
            {isLoading ? (
              <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
            ) : (
              <PaperAirplaneIcon className="w-5 h-5" />
            )}
          </button>
        )}
      </div>

      {/* Quick actions */}
      <div className="flex gap-2 px-3 pb-2 overflow-x-auto">
        {[
          { label: 'Signal BTC', action: 'What is the current signal for BTCUSD?' },
          { label: 'Analyze Gold', action: 'Analyze XAUUSD market conditions' },
          { label: 'Portfolio', action: 'Show my portfolio summary' },
          { label: 'AMD Phase', action: 'What AMD phase is Bitcoin in?' },
        ].map((quick) => (
          <button
            key={quick.label}
            type="button"
            onClick={() => onSendMessage(quick.action)}
            disabled={isLoading || disabled}
            className="px-3 py-1.5 text-xs bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-full whitespace-nowrap transition-colors disabled:opacity-50"
          >
            {quick.label}
          </button>
        ))}
      </div>
    </form>
  );
};

export default ChatInput;
