import { useState, useRef, useCallback } from 'react'
import { Send } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { StepResponseRequest } from '@/types/ai-session'

interface FlowPilotMessageBarProps {
  onRespond: (response: StepResponseRequest) => void
  disabled?: boolean
  isProcessing?: boolean
}

export function FlowPilotMessageBar({ onRespond, disabled = false, isProcessing = false }: FlowPilotMessageBarProps) {
  const [message, setMessage] = useState('')
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  const isDisabled = disabled || isProcessing

  const handleSubmit = useCallback(() => {
    const trimmed = message.trim()
    if (!trimmed || isDisabled) return
    onRespond({ free_text_input: trimmed })
    setMessage('')
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto'
    }
  }, [message, isDisabled, onRespond])

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

  const handleInput = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setMessage(e.target.value)
    const textarea = e.target
    textarea.style.height = 'auto'
    textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`
  }, [])

  return (
    <div
      className="fixed bottom-[68px] right-0 lg:right-72 z-40 px-4 sm:px-6 lg:px-8 pb-2"
      style={{ left: 'var(--sidebar-w, 0px)' }}
    >
      <div
        className={cn(
          'flex items-end gap-2 rounded-xl border p-3 transition-colors',
          isDisabled
            ? 'border-border/50 opacity-50'
            : 'border-border focus-within:border-[rgba(6,182,212,0.3)]'
        )}
        style={{ background: 'rgba(16, 17, 20, 0.95)', backdropFilter: 'blur(16px)' }}
      >
        <textarea
          ref={textareaRef}
          value={message}
          onChange={handleInput}
          onKeyDown={handleKeyDown}
          placeholder={isProcessing ? 'FlowPilot is thinking...' : 'Type a message...'}
          disabled={isDisabled}
          rows={1}
          className="flex-1 resize-none bg-transparent text-sm text-foreground placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed py-1.5 px-2"
        />
        <button
          onClick={handleSubmit}
          disabled={isDisabled || !message.trim()}
          aria-label="Send message"
          className={cn(
            'flex h-9 w-9 shrink-0 items-center justify-center rounded-lg transition-all',
            message.trim() && !isDisabled
              ? 'bg-gradient-brand text-[#101114] hover:opacity-90 active:scale-[0.97]'
              : 'bg-[rgba(255,255,255,0.04)] text-muted-foreground cursor-not-allowed'
          )}
        >
          <Send size={16} />
        </button>
      </div>
    </div>
  )
}
