import React, { useCallback, useEffect, useRef } from 'react'
import UserMessage from './UserMessage'
import AIMessage from './AIMessage'
import SystemMessage from './SystemMessage'
import InteractiveMessage from './InteractiveMessage'
import Avatar from './Avatar'
import { ChatConfig, Conversation, Message } from '@/types'
import { useLocalization } from '@/hooks/useLocalization'

interface MessageListProps {
  conversation: Conversation | null
  config: ChatConfig
  isLoading: boolean
  onEmailSubmit?: (email: string) => void
  onWhatsAppClick?: () => void
  aiName?: string
  aiAvatarUrl?: string
}

interface MessageRendererProps {
  message: Message
  config: ChatConfig
  onEmailSubmit?: (email: string) => void
  onWhatsAppClick?: () => void
}

const MessageRenderer: React.FC<MessageRendererProps> = ({ 
  message, 
  config, 
  onEmailSubmit, 
  onWhatsAppClick
}) => {
  switch (message.type) {
    case 'user':
      return <UserMessage message={message} config={config} />
    case 'ai':
      return <AIMessage message={message} config={config} />
    case 'system':
      return <SystemMessage message={message} />
    case 'interactive':
      return (
        <InteractiveMessage 
          message={message} 
          config={config}
          onEmailSubmit={onEmailSubmit}
          onWhatsAppClick={onWhatsAppClick}
        />
      )
    default:
      return <AIMessage message={message} config={config} />
  }
}

const LoadingIndicator: React.FC<{ config: ChatConfig; aiName?: string; aiAvatarUrl?: string }> = ({ config, aiName, aiAvatarUrl }) => {
  const { t } = useLocalization()
  
  return (
  <div className="lfc-flex lfc-justify-start lfc-mb-4">
    <div className="lfc-max-w-xs">
      <div className="lfc-flex lfc-items-center lfc-mb-1">
        <Avatar
          avatarUrl={aiAvatarUrl || config.avatarUrl}
          primaryColor={config.primaryColor}
          className="lfc-w-[38px] lfc-h-[38px] lfc-mr-2"
        />
        <span className="lfc-text-xs lfc-text-text-secondary">
          {aiName || config?.showName || t('chat.aiAssistant')}
        </span>
      </div>
      
      <div className="lfc-bg-bg-layer lfc-rounded-lg lfc-px-3 lfc-py-2">
        <div className="lfc-flex lfc-space-x-1">
          <div className="lfc-w-2 lfc-h-2 lfc-bg-text-tertiary lfc-rounded-full lfc-animate-bounce"></div>
          <div className="lfc-w-2 lfc-h-2 lfc-bg-text-tertiary lfc-rounded-full lfc-animate-bounce" style={{ animationDelay: '0.1s' }}></div>
          <div className="lfc-w-2 lfc-h-2 lfc-bg-text-tertiary lfc-rounded-full lfc-animate-bounce" style={{ animationDelay: '0.2s' }}></div>
        </div>
      </div>
    </div>
  </div>
  )
}

const MessageList: React.FC<MessageListProps> = ({ 
  conversation, 
  config, 
  isLoading, 
  onEmailSubmit, 
  onWhatsAppClick,
  aiName,
  aiAvatarUrl
}) => {
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const containerRef = useRef<HTMLDivElement>(null)

  // Robust auto-scroll to bottom when new messages arrive or loading state changes
  const scrollToBottom = useCallback(() => {
    const container = containerRef.current
    if (container) {
      try {
        container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' })
      } catch {
        container.scrollTop = container.scrollHeight
      }
    }
    if (messagesEndRef.current) {
      // Fallback to ensure we reach absolute bottom
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' })
    }
  }, [])

  useEffect(() => {
    // Use rAF to ensure DOM is committed before measuring heights
    const id = requestAnimationFrame(scrollToBottom)
    return () => cancelAnimationFrame(id)
  }, [conversation?.messages?.length, isLoading, scrollToBottom])

  // Initial mount scroll
  useEffect(() => {
    scrollToBottom()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <div 
      ref={containerRef}
      className="lfc-h-full lfc-overflow-y-auto lfc-p-4 lfc-space-y-2 lfc-scrollbar-thin lfc-scrollbar-thumb-gray-300 lfc-scrollbar-track-gray-100"
    >
      {conversation?.messages.map((message) => (
        <MessageRenderer
          key={message.id}
          message={message}
          config={config}
          onEmailSubmit={onEmailSubmit}
          onWhatsAppClick={onWhatsAppClick}
        />
      ))}

      {isLoading && <LoadingIndicator config={config} aiName={aiName} aiAvatarUrl={aiAvatarUrl} />}
      <div ref={messagesEndRef} />
    </div>
  )
}

export default MessageList