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

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

  const messagesList = useMemo(() => activeConversations[currentConversation.sn] || [], [activeConversations, currentConversation.sn]);
  console.log('messagesList----------------------------------------------------', messagesList);

  const messagesEndRef = useRef(null);
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messagesList, 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
          // className={message.sender === 'me' ? 'whatsappme-container' : ''}
          key={message.id}
          position={message.sender === 'me' ? 'right' : 'left'}
          {...message}
          onOpen={() => handlePreview(message)}
          // letterItem={{ id: 1, letter: 'AS' }}
          // 'waiting'| 'sent' | 'received' | 'read'
          styles={{ backgroundColor: message.sender === 'me' ? '#ccd5ae' : '' }}
          {...(message.sender === 'me'
            ? {
                style: { backgroundColor: '#ccd5ae' },
                notchStyle: { fill: '#ccd5ae' },
                className: 'whatsappme-container whitespace-pre-wrap',
              }
            : {})}
          // notchStyle={{fill: '#ccd5ae'}}
          // copiableDate={false}
        />
      ))}
      <Image src={previewSrc} preview={{ visible: previewVisible, src: previewSrc, onClose: onPreviewClose }} />
      <div ref={messagesEndRef}></div>
    </div>
  );
};

export default Messages;
