import { useEffect, useState, useRef, useMemo } from 'react';
import { Image, Alert } from 'antd';
import { MessageBox } from 'react-chat-elements';
import useConversationStore from '@/stores/ConversationStore';

const Messages = () => {
  const { activeConversations, currentConversation, setReferenceMsg } = useConversationStore();

  const messagesList = useMemo(() => (activeConversations[currentConversation.sn] || []).map(message => ({
    ...message,
    key: message.id,
    position: message.sender === 'me' ? 'right' : 'left',
    onOpen: () => handlePreview(message),
    ...(message.sender === 'me' ? {
      styles: { backgroundColor: '#ccd4ae' } ,
      notchStyle: { fill: '#ccd4ae'},
      replyButton: ['text'].includes(message.whatsapp_msg_type) && message.status !== 'failed' ? true : false,
      onReplyClick: () => (setReferenceMsg(message)),
      className: 'whatsappme-container whitespace-pre-wrap',
    } : {
      replyButton: ['text'].includes(message.whatsapp_msg_type) ? true : false,
      onReplyClick: () => (setReferenceMsg(message)),
    }),
  })), [activeConversations, currentConversation.sn]);
  console.log('messagesList----------------------------------------------------', messagesList);

  const messagesEndRef = useRef(null);
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [currentConversation.last_received_time]);

  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewSrc, setPreviewSrc] = useState();
  const onPreviewClose = () => {
    setPreviewSrc('');
    setPreviewVisible(false);
  };
  const handlePreview = (msg) => {
    if (msg.type !== 'photo') {
      return false;
    }
    setPreviewVisible(true);
    setPreviewSrc(msg.data.uri);
  };

  return (
    <div>
      {messagesList.map((message, index) => (
        <MessageBox key={message.key}
          {...message}
        />
      ))}
      <Image src={previewSrc} preview={{ visible: previewVisible, src: previewSrc, onClose: onPreviewClose }} />
      <div ref={messagesEndRef}></div>
    </div>
  );
};

export default Messages;
