import { useState } from 'react'
import type { KeyboardEvent } from 'react'
import { Textarea } from '@/components/ui/textarea'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { useChatStore } from '@/store/useChatStore'
import { useConnectionStore } from '@/store/useConnectionStore'
import { SendHorizontal, AlertCircle, Clock, Mic } from 'lucide-react'

export function ChatBottombar() {
  const [input, setInput] = useState('')
  const sendMessage = useChatStore((state) => state.sendMessage)
  const connectionStatus = useConnectionStore((state) => state.status)
  const queuedCount = useConnectionStore((state) => state.queuedCount)

  const isQueueFull = queuedCount >= 20
  const isDisconnected = connectionStatus === 'disconnected' || connectionStatus === 'error'

  const handleSend = () => {
    if (!input.trim() || isQueueFull) return
    sendMessage(input.trim())
    setInput('')
  }

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

  return (
    <div className="p-3 bg-transparent">
      <div className="max-w-3xl mx-auto flex flex-col gap-2">
        <div className="relative flex items-center gap-2 bg-secondary/60 backdrop-blur-md border border-border/60 rounded-full px-4 py-1.5 shadow-sm focus-within:ring-1 focus-within:ring-primary/30 focus-within:border-primary/40 transition-all">
          <Textarea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={
              isQueueFull
                ? 'Mất kết nối. Hàng chờ đã đầy, vui lòng chờ...'
                : 'Hỏi Loyalty Agent...'
            }
            className="flex-1 min-h-[36px] max-h-[120px] py-1.5 px-1 bg-transparent border-0 focus-visible:ring-0 focus-visible:ring-offset-0 text-sm leading-relaxed text-foreground placeholder:text-muted-foreground/60 resize-none overflow-y-auto"
            rows={1}
            disabled={isQueueFull}
          />

          <div className="flex items-center gap-1 shrink-0">
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 rounded-full text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors"
                    type="button"
                  >
                    <Mic className="w-4 h-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent side="top">
                  <p className="text-xs">Nhập bằng giọng nói</p>
                </TooltipContent>
              </Tooltip>

              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    size="icon"
                    className="h-8 w-8 rounded-full bg-primary hover:bg-primary/90 text-primary-foreground shadow-sm disabled:opacity-30 shrink-0 transition-all active:scale-95"
                    onClick={handleSend}
                    disabled={!input.trim() || isQueueFull}
                  >
                    <SendHorizontal className="w-4 h-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent side="top">
                  <p className="text-xs">Gửi tin nhắn (Enter)</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          </div>
        </div>

        {/* Offline status or queued indicator */}
        {isDisconnected && (
          <div className="flex items-center justify-between text-xs text-destructive bg-destructive/10 border border-destructive/20 px-3 py-1.5 rounded-full shadow-sm">
            <div className="flex items-center gap-1.5">
              <AlertCircle className="w-3.5 h-3.5 shrink-0" />
              <span>Mất kết nối với máy chủ. Đang tự động thử lại...</span>
            </div>
            {queuedCount > 0 && (
              <div className="flex items-center gap-1 text-amber-500 font-medium">
                <Clock className="w-3.5 h-3.5" />
                <span>Đã lưu tạm {queuedCount} tin nhắn</span>
              </div>
            )}
          </div>
        )}

        <p className="text-[11px] text-muted-foreground/70 text-center py-0.5 select-none">
          Loyalty Agent có thể đưa ra câu trả lời không chính xác. Hãy kiểm tra lại thông tin quan trọng.
        </p>
      </div>
    </div>
  )
}

