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

const Messages = () => {
  const { currentConversation, setReferenceMsg, msgListLoading,  } = useConversationStore();
  const activeMessages = useConversationStore(useShallow((state) => (currentConversation.sn ? state.activeConversations[currentConversation.sn] : [])));

  const messagesList = useMemo(
    () =>
      (activeMessages || []).map((message) => ({
        ...message,
        key: message.id,
        position: message.sender === 'me' ? 'right' : 'left',
        ...(message.sender === 'me'
          ? {
              styles: { backgroundColor: '#ccd4ae' },
              notchStyle: { fill: '#ccd4ae' },
              replyButton: ['text'].includes(message.whatsapp_msg_type) && message.status !== 'failed' ? true : false,
              className: 'whatsappme-container whitespace-pre-wrap',
            }
          : {
              replyButton: ['text'].includes(message.whatsapp_msg_type) ? true : false,
            }),
      })),
    [activeMessages, 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>
    <Spin spinning={msgListLoading} tip={'正在读取...'} wrapperClassName='pt-8 ' >
      {messagesList.map((message, index) => (
        <MessageBox key={message.key} {...message} onReplyClick={() => setReferenceMsg(message)} onOpen={() => handlePreview(message)} />
      ))}
      <Image src={previewSrc} preview={{ visible: previewVisible, src: previewSrc, onClose: onPreviewClose }} />
      <div ref={messagesEndRef}></div>
    </Spin>
    </div>
  );
};

export default Messages;
