import React, { useState, useRef, KeyboardEvent, useEffect } from 'react'
import { ChatConfig } from '@/types'
import { useLocalization } from '@/hooks/useLocalization'

interface MessageInputProps {
  onSendMessage: (message: string) => void
  disabled: boolean
  config: ChatConfig
}

const MessageInput: React.FC<MessageInputProps> = ({ onSendMessage, disabled, config }) => {
  const [message, setMessage] = useState('')
  const inputRef = useRef<HTMLTextAreaElement>(null)
  const baselineHeightRef = useRef<number | null>(null)
  const { t } = useLocalization()

  const handleSend = () => {
    const trimmedMessage = message.trim()
    if (trimmedMessage && !disabled) {
      onSendMessage(trimmedMessage)
      setMessage('')
      
      // Focus back to input after sending
      setTimeout(() => {
        inputRef.current?.focus()
      }, 100)
    }
  }

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

  // Auto-grow textarea height up to a reasonable max
  useEffect(() => {
    const element = inputRef.current
    if (!element) return
    element.style.height = 'auto'
    const maxHeightPx = 110 // ~8 lines depending on line-height
    const newHeight = Math.min(element.scrollHeight, maxHeightPx)
    element.style.height = `${newHeight}px`
  }, [message])

  // Capture baseline single-line height on mount (when message is empty)
  useEffect(() => {
    const element = inputRef.current
    if (!element) return
    // Ensure one-line baseline
    const prev = element.value
    element.style.height = 'auto'
    element.value = ''
    baselineHeightRef.current = element.scrollHeight
    element.value = prev
  }, [])

  const getSendButtonStyle = () => {
    const baseStyle: React.CSSProperties = {}
    
    if (config.primaryColor && !disabled && message.trim()) {
      baseStyle.backgroundColor = config.primaryColor
      baseStyle.borderColor = config.primaryColor
    }
    
    return baseStyle
  }

  return (
    <div className="lfc-p-4">
      <div className="lfc-flex lfc-items-end lfc-space-x-2">
        <div className="lfc-flex-1 lfc-flex">
          <textarea
            ref={inputRef}
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={disabled ? t('chat.loading') : t('chat.placeholder')}
            disabled={disabled}
            rows={1}
            wrap="soft"
            className={`
              lfc-w-full lfc-px-3 lfc-py-2 lfc-border lfc-border-border-subtle lfc-rounded-lg 
              focus:lfc-outline-none focus:lfc-ring-2 focus:lfc-ring-border-focus focus:lfc-border-transparent
              disabled:lfc-bg-bg-layer disabled:lfc-text-text-secondary disabled:lfc-cursor-not-allowed
              lfc-text-sm lfc-resize-none lfc-leading-5
              lfc-transition-colors lfc-duration-200
            `}
            style={{ maxHeight: 110, overflowY: 'hidden' }}
            maxLength={500}
            autoComplete="off"
          />
          
          {/* Character counter */}
          {message.length > 400 && (
            <div className="lfc-text-xs lfc-text-text-tertiary lfc-mt-1 lfc-text-right">
              {message.length}/500
            </div>
          )}
        </div>
        
        <button
          onClick={handleSend}
          disabled={disabled || !message.trim()}
          className={`
            lfc-h-[36px]
            lfc-px-4 lfc-py-2 lfc-rounded-lg lfc-font-medium lfc-text-sm
            lfc-transition-all lfc-duration-200
            focus:lfc-outline-none focus:lfc-ring-2 focus:lfc-ring-primary-300 focus:lfc-ring-offset-2
            ${disabled || !message.trim() 
              ? 'lfc-bg-gray-300 lfc-text-gray-500 lfc-cursor-not-allowed' 
              : 'lfc-bg-primary-500 hover:lfc-bg-primary-600 lfc-text-white hover:lfc-shadow-md active:lfc-scale-95'
            }
          `}
          style={getSendButtonStyle()}
          aria-label="Send message"
        >
          {disabled ? (
            <svg className="lfc-w-4 lfc-h-4 lfc-animate-spin" fill="none" viewBox="0 0 24 24">
              <circle className="lfc-opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
              <path className="lfc-opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
          ) : (
            <svg className="lfc-w-4 lfc-h-4 lfc-transform lfc-rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
            </svg>
          )}
        </button>
      </div>
    </div>
  )
}

export default MessageInput