import { useRef, useEffect, useState } from 'react'
import type { UIEvent } from 'react'
import { ChatBubble } from './ChatBubble'

import { WelcomeScreen } from './WelcomeScreen'
import type { Message } from '@/store/useChatStore'
import { ArrowDown } from 'lucide-react'
import { Button } from '@/components/ui/button'

export function ChatList({ messages }: { messages: Message[] }) {
  const scrollRef = useRef<HTMLDivElement>(null)
  const bottomRef = useRef<HTMLDivElement>(null)
  const [showScrollBottom, setShowScrollBottom] = useState(false)
  const isAtBottomRef = useRef(true)

  const handleScroll = (e: UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget
    const distanceFromBottom = scrollHeight - scrollTop - clientHeight
    const isAtBottom = distanceFromBottom <= 100
    isAtBottomRef.current = isAtBottom
    setShowScrollBottom(!isAtBottom && messages.length > 0)
  }

  const scrollToBottom = (smooth = true) => {
    bottomRef.current?.scrollIntoView({ behavior: smooth ? 'smooth' : 'auto' })
  }

  useEffect(() => {
    if (isAtBottomRef.current) {
      scrollToBottom()
    }
  }, [messages])

  if (messages.length === 0) {
    return <WelcomeScreen />
  }

  return (
    <div
      ref={scrollRef}
      onScroll={handleScroll}
      className="flex-1 w-full p-4 overflow-y-auto custom-scrollbar relative"
    >
      <div className="flex flex-col gap-2 pb-6 max-w-3xl mx-auto">
        {messages.map((msg) => (
          <ChatBubble key={msg.id} message={msg} />
        ))}
        <div ref={bottomRef} />
      </div>

      {showScrollBottom && (
        <div className="sticky bottom-4 left-1/2 -translate-x-1/2 flex justify-center z-10 animate-in fade-in slide-in-from-bottom-2">
          <Button
            size="sm"
            variant="secondary"
            className="rounded-full shadow-lg border border-white/10 gap-1.5 bg-secondary/90 hover:bg-secondary text-xs backdrop-blur-md"
            onClick={() => scrollToBottom(true)}
          >
            <ArrowDown className="w-3.5 h-3.5" />
            <span>Tin nhắn mới</span>
          </Button>
        </div>
      )}
    </div>
  )
}
