import React, { useState, type FormEvent, type KeyboardEvent } from 'react'

export interface QueryInputProps {
  onSubmit: (question: string) => void
  isLoading: boolean
}

export const QueryInput: React.FC<QueryInputProps> = ({ onSubmit, isLoading }) => {
  const [question, setQuestion] = useState<string>('')

  const handleSubmit = (e: FormEvent): void => {
    e.preventDefault()
    const trimmed = question.trim()
    if (trimmed && !isLoading) {
      onSubmit(trimmed)
      setQuestion('')
    }
  }

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

  const isDisabled = isLoading || question.trim() === ''

  return (
    <form onSubmit={handleSubmit} className="space-y-3">
      <textarea
        value={question}
        onChange={(e) => setQuestion(e.target.value)}
        onKeyDown={handleKeyDown}
        placeholder="Ask a question about your documents..."
        disabled={isLoading}
        rows={3}
        className="w-full rounded border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
      />
      <button
        type="submit"
        disabled={isDisabled}
        className="px-4 py-2 bg-blue-600 text-white font-medium rounded hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-blue-600 transition-all duration-200"
      >
        {isLoading ? 'Processing...' : 'Submit'}
      </button>
    </form>
  )
}
