"use strict";

/** @format */

import React, { useState, useEffect, useCallback } from 'react';
import { ChatContainer, NonRoomChat } from '../styled/StyledComponents';
import { useDispatch } from 'react-redux';
import MessageList from './MessageList';
import SendInput from '../styled/SendInput';
import { deleteRoomMessage, setEditAction, setLastViewedTimestamp } from '../../roomStore/roomsSlice';
import Loader from '../styled/Loader';
import { useXmppClient } from '../../context/xmppProvider';
import ChatHeader from './ChatHeader';
import NoMessagesPlaceholder from './NoMessagesPlaceholder';
import NewChatModal from '../Modals/NewChatModal/NewChatModal';
import { EditWrapper } from './EditWrapper';
import { NoSelectedChatIcon } from '../../assets/icons';
import { ChooseChatMessage } from './ChooseChatMessage';
import { useSendMessage } from '../../hooks/useSendMessage';
import { useRoomInitialization } from '../../hooks/useRoomInitialization';
import { useRoomState } from '../../hooks/useRoomState';
import { useChatSettingState } from '../../hooks/useChatSettingState';
import CustomTypingIndicator from '../styled/StyledInputComponents/CustomTypingIndicator';
// import {PanGestureHandler} from 'react-native-gesture-handler';

import { Platform, View } from 'react-native';
import { KeyboardAvoidingView } from 'react-native-keyboard-controller';
import useComposing from '../../hooks/useComposing';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const ChatRoom = /*#__PURE__*/React.memo(({
  CustomMessageComponent,
  CustomInputComponent,
  CustomScrollableArea,
  CustomDaySeparator,
  CustomNewMessageLabel,
  handleBackClick,
  eventHandlers: propsEventHandlers
}) => {
  const {
    client
  } = useXmppClient();
  const dispatch = useDispatch();
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const {
    user,
    config: storeConfig
  } = useChatSettingState();

  // Merge eventHandlers from props with config (props take precedence)
  // This is necessary because functions can't be stored in Redux
  const configWithEventHandlers = React.useMemo(() => {
    if (propsEventHandlers && storeConfig) {
      return {
        ...storeConfig,
        eventHandlers: propsEventHandlers
      };
    }
    return storeConfig;
  }, [storeConfig, propsEventHandlers]);
  const {
    roomsList,
    activeRoomJID,
    editAction,
    loading,
    globalLoading,
    roomMessages
  } = useRoomState();
  const {
    sendMessage: sendMs,
    sendMedia: sendMessageMedia,
    sendEditMessage,
    isLastMessageFromUserAndProcessing
  } = useSendMessage(configWithEventHandlers);
  const {
    sendStartComposing,
    sendEndComposing
  } = useComposing(configWithEventHandlers || storeConfig);
  const sendMessage = useCallback(message => {
    if (!activeRoomJID) {
      return;
    }
    dispatch(setLastViewedTimestamp({
      chatJID: activeRoomJID,
      timestamp: 0
    }));
    sendMs(message, activeRoomJID);
  }, [activeRoomJID]);
  const sendMedia = useCallback((data, type) => {
    // Return the promise so callers can sequence the follow-up
    // text send AFTER the upload finishes (consumer expectation:
    // media first, text second — never interleaved).
    return sendMessageMedia(data, type, activeRoomJID || '');
  }, [activeRoomJID]);
  const loadMoreMessages = useCallback(async (chatJID, max, idOfMessageBefore) => {
    if (isLoadingMore || roomsList?.[chatJID]?.historyComplete) {
      return;
    }
    const lastMsgId = typeof idOfMessageBefore !== 'string' ? idOfMessageBefore : Number(roomsList[chatJID].messages[roomsList[chatJID].messages.length - 2]?.id);
    setIsLoadingMore(true);
    try {
      // Return the promise so MessageList's `await loadMoreMessages`
      // actually waits for MAM to respond before its own onEndReached
      // re-arms — otherwise the awaited call resolves with `undefined`
      // immediately and rapid scrolls fire repeat requests that step
      // on each other.
      await client?.getHistoryStanza(chatJID, max, lastMsgId);
    } finally {
      setIsLoadingMore(false);
    }
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [client?.client?.jid, isLoadingMore, roomsList]);
  const onCloseEdit = () => {
    dispatch(setEditAction({
      isEdit: false
    }));
  };
  useEffect(() => {
    if (!activeRoomJID) {
      return;
    }
    dispatch(setLastViewedTimestamp({
      chatJID: activeRoomJID,
      timestamp: 0
    }));
    setIsLoadingMore(false);
    return () => {
      if (client) {
        client.actionSetTimestampToPrivateStoreStanza(activeRoomJID, new Date().getTime(), Object.keys(roomsList));
      }
      dispatch(setLastViewedTimestamp({
        chatJID: activeRoomJID,
        timestamp: new Date().getTime()
      }));
      dispatch(deleteRoomMessage({
        roomJID: activeRoomJID,
        messageId: 'delimiter-new'
      }));
      setIsLoadingMore(false);
    };
  }, [activeRoomJID]);

  // hooks useEffects
  // useRoomUrl(activeRoomJID || "", roomsList, config);

  useRoomInitialization(activeRoomJID || '', roomsList, configWithEventHandlers || storeConfig || {}, roomMessages.length);
  if (Object.keys(roomsList)?.length < 1 && !loading && !globalLoading) {
    return /*#__PURE__*/_jsx(NonRoomChat, {
      children: /*#__PURE__*/_jsx(NewChatModal, {})
    });
  }
  if (!activeRoomJID || !roomsList?.[activeRoomJID]) {
    return /*#__PURE__*/_jsx(ChooseChatMessage, {});
  }
  return /*#__PURE__*/_jsx(KeyboardAvoidingView, {
    style: {
      flex: 1
    },
    behavior: Platform.OS === 'ios' ? 'padding' : 'height',
    keyboardVerticalOffset: configWithEventHandlers?.keyboardVerticalOffset ?? 0,
    children: /*#__PURE__*/_jsxs(ChatContainer, {
      style: configWithEventHandlers?.chatRoomStyles ? configWithEventHandlers.chatRoomStyles : undefined,
      children: [!configWithEventHandlers?.disableHeader && /*#__PURE__*/_jsx(ChatHeader, {
        currentRoom: roomsList[activeRoomJID],
        handleBackClick: handleBackClick
      }), configWithEventHandlers?.chatHeaderAdditional?.enabled && configWithEventHandlers.chatHeaderAdditional.element(), /*#__PURE__*/_jsx(View, {
        style: {
          flex: 1
        },
        children: loading || globalLoading ? /*#__PURE__*/_jsx(View, {
          style: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center'
          },
          children: /*#__PURE__*/_jsx(Loader, {
            color: configWithEventHandlers?.colors?.primary
          })
        }) : Object.keys(roomsList).length < 1 || !activeRoomJID ? /*#__PURE__*/_jsx(View, {
          style: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center'
          },
          children: /*#__PURE__*/_jsx(NoSelectedChatIcon, {})
        }) : !roomMessages || roomMessages.length === 0 ? /*#__PURE__*/_jsx(View, {
          style: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#ffffff'
          },
          children: /*#__PURE__*/_jsx(NoMessagesPlaceholder, {})
        }) : CustomScrollableArea ? /*#__PURE__*/_jsx(CustomScrollableArea, {
          roomJID: activeRoomJID,
          messages: roomMessages,
          decoratedMessages: roomMessages.map((msg, idx) => ({
            message: msg,
            showDateLabel: idx === 0 || new Date(msg.date).toDateString() !== new Date(roomMessages[idx - 1]?.date).toDateString()
          })),
          isLoading: isLoadingMore,
          isReply: false,
          loadMoreMessages: loadMoreMessages,
          renderMessage: decorated => CustomMessageComponent ? /*#__PURE__*/_jsx(CustomMessageComponent, {
            message: decorated.message,
            isUser: decorated.message.user.id === user.xmppUsername,
            isReply: false
          }) : null,
          scrollController: {
            scrollToBottom: () => {},
            waitForImagesLoaded: async () => {},
            showScrollButton: false,
            newMessagesCount: 0,
            resetNewMessageCounter: () => {}
          },
          typingIndicator: roomsList[activeRoomJID]?.composing ? configWithEventHandlers?.customTypingIndicator?.customComponent ? /*#__PURE__*/_jsx(configWithEventHandlers.customTypingIndicator.customComponent, {
            usersTyping: roomsList[activeRoomJID]?.composingList || [],
            text: typeof configWithEventHandlers.customTypingIndicator.text === 'function' ? configWithEventHandlers.customTypingIndicator.text(roomsList[activeRoomJID]?.composingList || []) : configWithEventHandlers.customTypingIndicator.text || 'Typing...',
            isVisible: true
          }) : null : undefined,
          config: configWithEventHandlers
        }) : /*#__PURE__*/_jsx(MessageList, {
          loadMoreMessages: loadMoreMessages,
          CustomMessage: CustomMessageComponent,
          CustomDaySeparator: CustomDaySeparator,
          CustomNewMessageLabel: CustomNewMessageLabel,
          user: user,
          roomJID: activeRoomJID,
          config: configWithEventHandlers,
          loading: isLoadingMore,
          isReply: false
        })
      }), editAction && editAction.isEdit && /*#__PURE__*/_jsx(EditWrapper, {
        text: editAction.text || '',
        onClose: onCloseEdit
      }), CustomInputComponent ? /*#__PURE__*/_jsx(CustomInputComponent, {
        sendMessage: editAction && editAction.isEdit ? sendEditMessage : sendMessage,
        sendMedia: sendMedia,
        config: configWithEventHandlers,
        isLoading: loading,
        onFocus: sendStartComposing,
        onBlur: sendEndComposing,
        isMessageProcessing: isLastMessageFromUserAndProcessing(activeRoomJID),
        editMessage: editAction && editAction.text
      }) : /*#__PURE__*/_jsx(SendInput, {
        editMessage: editAction && editAction.text,
        sendMessage: editAction && editAction.isEdit ? sendEditMessage : sendMessage,
        sendMedia: sendMedia,
        config: configWithEventHandlers,
        isLoading: loading,
        onFocus: sendStartComposing,
        onBlur: sendEndComposing,
        isMessageProcessing: isLastMessageFromUserAndProcessing(activeRoomJID)
      }), configWithEventHandlers?.customTypingIndicator?.enabled && (configWithEventHandlers.customTypingIndicator.position === 'overlay' || configWithEventHandlers.customTypingIndicator.position === 'floating') && roomsList[activeRoomJID]?.composing && /*#__PURE__*/_jsx(CustomTypingIndicator, {
        usersTyping: roomsList[activeRoomJID]?.composingList || ['User'],
        text: configWithEventHandlers.customTypingIndicator.text,
        position: configWithEventHandlers.customTypingIndicator.position,
        styles: configWithEventHandlers.customTypingIndicator.styles,
        customComponent: configWithEventHandlers.customTypingIndicator.customComponent,
        isVisible: roomsList[activeRoomJID]?.composing || false
      })]
    })
  });
});
export default ChatRoom;
//# sourceMappingURL=ChatRoom.js.map