import { useRef, useState, useEffect } from 'react';
import useConversationStore from '@/stores/ConversationStore';
import { useShallow } from 'zustand/react/shallow';
import { Image, } from 'antd';
import MessagesList from './MessagesList';
import { fetchCleanUnreadMsgCount, fetchMessages, MESSAGE_PAGE_SIZE } from '@/actions/ConversationActions';

const MessagesWrapper = () => {
  const [currentConversation, updateCurrentConversation] = useConversationStore(useShallow((state) => [state.currentConversation, state.updateCurrentConversation]));
  const activeMessages = useConversationStore(useShallow((state) => (state.currentConversation.sn && state.activeConversations[state.currentConversation.sn] ? state.activeConversations[state.currentConversation.sn]: [])));

  const [longList, setLongList] = useState([]);
  const [longListLoading, setLongListLoading] = useState(false);
  const [shouldScrollBottom, setShouldScrollBottom] = useState(true);
  useEffect(() => {
    setLongList(activeMessages);
    setShouldScrollBottom(true);
    if (currentConversation.opi_sn && currentConversation.whatsapp_phone_number && activeMessages.length > 0) {
      fetchCleanUnreadMsgCount({ opisn: currentConversation.opi_sn, whatsappid: currentConversation.whatsapp_phone_number });
    }

    return () => {};
  }, [activeMessages, currentConversation.sn]);

  const getMoreMessages = async () => {
    setShouldScrollBottom(false);
    setLongListLoading(true);
    const data = await fetchMessages({ opisn: currentConversation.opi_sn, whatsappid: currentConversation.whatsapp_phone_number, lasttime: currentConversation?.lasttime || '' });
    setLongListLoading(false);
    setLongList(prevValue => data.concat(prevValue));
    const thisLastTime = data.length > 0 ? data[0].orgmsgtime : '';
    const loadNextPage = !(data.length === 0 || data.length < MESSAGE_PAGE_SIZE);
    updateCurrentConversation({ lasttime: thisLastTime, loadNextPage });
    return data.length;
  };

  const reference = useRef(null);

  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewSrc, setPreviewSrc] = useState();
  const onPreviewClose = () => {
    setPreviewSrc('');
    setPreviewVisible(false);
  };
  const handlePreview = (msg) => {
    switch (msg.whatsapp_msg_type) {
      case 'image':
        setPreviewVisible(true);
        setPreviewSrc(msg.data.uri);
        return false;

      case 'document':
        window.open(msg.data.link || msg.data.uri, '_blank', 'noopener,noreferrer');
        return false;

      default:
        return false;
    }
  };
  return (
    <>
      <MessagesList messages={longList} dataSourceLen={longList.length} {...{ reference, handlePreview, longListLoading, setLongListLoading, getMoreMessages, shouldScrollBottom, loadNextPage: currentConversation?.loadNextPage ?? true }} />
      <Image width={0} height={0} src={null} preview={{ visible: previewVisible, src: previewSrc, onClose: onPreviewClose }} />
    </>
  );
};
export default MessagesWrapper;
