'use client'

import { useRef, useState } from 'react'
import { EmojiPicker } from './EmojiPicker'

interface ChatInputProps {
  onSend: (text: string) => void
  disabled?: boolean
  lobsterId?: string
}

export function ChatInput({ onSend, disabled, lobsterId }: ChatInputProps) {
  const [text, setText] = useState('')
  const [showEmojiPicker, setShowEmojiPicker] = useState(false)
  const inputRef = useRef<HTMLTextAreaElement>(null)

  const handleSend = () => {
    const trimmed = text.trim()
    if (!trimmed) return
    onSend(trimmed)
    setText('')
    inputRef.current?.focus()
  }

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

  const handleEmojiSelect = (emojiUrl: string) => {
    // 插入表情图片的markdown格式
    const emojiMarkdown = `![emoji](${emojiUrl})`
    const newText = text + (text ? ' ' : '') + emojiMarkdown
    setText(newText)
    inputRef.current?.focus()
  }

  return (
    <div className="border-t border-slate-200 px-4 py-3">
      <div className="flex items-end gap-2">
        {lobsterId && (
          <div className="relative">
            <button
              onClick={() => setShowEmojiPicker(!showEmojiPicker)}
              disabled={disabled}
              className="rounded-xl border border-slate-300 px-3 py-2.5 text-sm hover:bg-slate-50 disabled:opacity-50"
              title="选择表情"
            >
              😊
            </button>
            {showEmojiPicker && (
              <EmojiPicker
                apikeyId={lobsterId}
                onSelect={handleEmojiSelect}
                onClose={() => setShowEmojiPicker(false)}
              />
            )}
          </div>
        )}
        <textarea
          ref={inputRef}
          value={text}
          onChange={e => setText(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="Type a message..."
          disabled={disabled}
          rows={1}
          className="flex-1 resize-none rounded-xl border border-slate-300 px-4 py-2.5 text-sm focus:border-blue-500 focus:outline-none disabled:opacity-50"
        />
        <button
          onClick={handleSend}
          disabled={disabled || !text.trim()}
          className="rounded-xl bg-blue-600 px-5 py-2.5 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
        >
          Send
        </button>
      </div>
    </div>
  )
}
