"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _styledModalComponents = require("../styledModalComponents");
var _icons = require("../../../assets/icons");
var _ModalHeaderComponent = _interopRequireDefault(require("../ModalHeaderComponent"));
var _ProfileImagePlaceholder = require("../../MainComponents/ProfileImagePlaceholder");
var _Button = _interopRequireDefault(require("../../styled/Button"));
var _DropdownMenu = _interopRequireDefault(require("../../DropdownMenu/DropdownMenu"));
var _chatSettingsSlice = require("../../../roomStore/chatSettingsSlice");
var _roomsSlice = require("../../../roomStore/roomsSlice");
var _EditUserModal = _interopRequireDefault(require("./EditUserModal"));
var _walletUsername = require("../../../helpers/walletUsername");
var _xmppProvider = require("../../../context/xmppProvider");
var _Select = _interopRequireDefault(require("../../MainComponents/Select"));
var _hooks = require("../../../hooks/hooks");
var _reactNative = require("react-native");
var _rooms = require("../../../networking/api-requests/rooms.api");
var _createRoomFromApi = require("../../../helpers/createRoomFromApi");
var _ToastContext = require("../../../context/ToastContext");
var _LANGUAGE_OPTIONS = require("../../../helpers/constants/LANGUAGE_OPTIONS");
var _user = require("../../../networking/api-requests/user.api");
var _useChatSettingState = require("../../../hooks/useChatSettingState");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
const UserProfileModal = ({
  handleCloseModal
}) => {
  const dispatch = (0, _hooks.useAppDispatch)();
  const {
    client
  } = (0, _xmppProvider.useXmppClient)();
  const {
    showToast
  } = (0, _ToastContext.useToast)();
  const {
    config,
    user,
    selectedUser,
    langSource
  } = (0, _useChatSettingState.useChatSettingState)();
  const [isEditing, setIsEditing] = (0, _react.useState)(false);
  const [documents, setDocuments] = (0, _react.useState)([]);
  const [deleteDocumentId, setDeleteDocumentId] = (0, _react.useState)('');
  const [showDelete, setShowDelete] = (0, _react.useState)(false);
  const handleDeleteDocument = async () => {
    try {
      await (0, _user.deleteDocument)(deleteDocumentId);
      setDocuments(documents.filter(doc => doc._id !== deleteDocumentId));
      showToast({
        id: Date.now().toString(),
        title: 'Success',
        message: 'Document deleted successfully',
        type: 'success'
      });
      // handleGetDocs();
    } catch (error) {
      console.error('Error deleting document', error);
      showToast({
        id: Date.now().toString(),
        title: 'Error',
        message: 'Failed to delete document',
        type: 'error'
      });
    } finally {
      setShowDelete(false);
    }
  };
  const handleGetDocs = async () => {
    try {
      const {
        data
      } = await (0, _user.getDocuments)(user?.defaultWallet?.walletAddress);
      const items = data.results.filter(el => el.locations[0]);
      setDocuments(items);
    } catch (error) {
      console.error('Error getting docs', error);
    }
  };
  (0, _react.useEffect)(() => {
    handleGetDocs();
  }, []);
  const handleBackClick = (0, _react.useCallback)(() => {
    dispatch((0, _chatSettingsSlice.setSelectedUser)(undefined));
    handleCloseModal();
  }, []);
  const handleLogout = (0, _react.useCallback)(() => {
    dispatch((0, _chatSettingsSlice.logout)());
    dispatch((0, _roomsSlice.setLogoutState)());
  }, []);
  const menuOptions = (0, _react.useMemo)(() => [{
    label: 'Log Out',
    icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.LeaveIcon, {}),
    onClick: () => {
      handleLogout();
    },
    styles: {
      color: 'red'
    }
  }], []);
  const handleSelect = selected => {
    dispatch((0, _chatSettingsSlice.setLangSource)(selected.id));
  };
  const EditClick = (0, _react.useCallback)(() => {
    setIsEditing(true);
  }, []);
  const handleRoomCreation = async (newChat, usersArrayLength) => {
    try {
      const normalizedChat = (0, _createRoomFromApi.createRoomFromApi)(newChat, config?.xmppSettings?.conference, usersArrayLength);
      if (!normalizedChat || !client) return;
      dispatch((0, _roomsSlice.addRoomViaApi)({
        room: normalizedChat,
        xmpp: client
      }));
      dispatch((0, _roomsSlice.setCurrentRoom)({
        roomJID: normalizedChat?.jid || ''
      }));
      showToast({
        id: Date.now().toString(),
        title: 'Success!',
        message: 'Room created succusfully!',
        type: 'success',
        duration: 3000
      });
    } catch (error) {
      console.error('Error handling room creation:', error);
    }
  };
  const handlePrivateMessage = (0, _react.useCallback)(async () => {
    showToast({
      id: Date.now().toString(),
      title: 'Room creation',
      message: 'Room is being created...',
      type: 'info',
      duration: 3000
    });
    let newRoomJid = '';
    if (config?.newArch) {
      const newRoom = await (0, _rooms.postPrivateRoom)(selectedUser?.userJID ?? (selectedUser?.id || ''));
      handleRoomCreation(newRoom, 2);
      newRoomJid = newRoom.name;
    } else {
      const selectedUserUsername = (0, _walletUsername.walletToUsername)(selectedUser?.id || '');
      const myUsername = (0, _walletUsername.walletToUsername)(user.defaultWallet.walletAddress);
      const combinedWalletAddress = [myUsername, selectedUserUsername].sort().join('.');
      const roomJid = combinedWalletAddress.toLowerCase();
      const combinedUsersName = [user.firstName, selectedUser?.name?.split(' ')?.[0] || ''].sort().join(' and ');
      newRoomJid = (await client?.createPrivateRoomStanza(combinedUsersName, `Private chat ${combinedUsersName}`, roomJid)) || '';
      if (newRoomJid) {
        await client?.inviteRoomRequestStanza(selectedUserUsername, newRoomJid);
        await client?.getRoomsStanza();
      }
    }
    dispatch((0, _chatSettingsSlice.setActiveModal)(undefined));
  }, [selectedUser]);
  const modalUser = selectedUser ?? user;
  const findLanguage = () => {
    if (!langSource) {
      return null;
    }
    const language = _LANGUAGE_OPTIONS.LANGUAGE_OPTIONS.find(lang => lang.id === langSource);
    return language || null;
  };
  const showDeleteModal = docId => {
    setDeleteDocumentId(docId);
    setShowDelete(true);
  };
  const DefaultBody = (0, _react.useMemo)(() => /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_ModalHeaderComponent.default, {
      handleCloseModal: handleBackClick,
      headerTitle: 'Profile',
      rightMenu: !selectedUser && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
          onPress: EditClick,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.EditIcon, {
            color: "#8C8C8C"
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_DropdownMenu.default, {
          options: menuOptions,
          position: "right",
          menuIcon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.MoreIcon, {})
        })]
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.CenterContainer, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_ProfileImagePlaceholder.ProfileImagePlaceholder, {
        icon: modalUser?.profileImage ?? null,
        name: modalUser?.name ?? modalUser?.firstName,
        size: 120
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.UserInfo, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.UserName, {
          children: modalUser?.name ? `${modalUser?.name}` : `${modalUser?.firstName} ${modalUser?.lastName}`
        })
      }), !selectedUser && config?.translates?.enabled && /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.BorderedContainer, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Select.default, {
          options: _LANGUAGE_OPTIONS.LANGUAGE_OPTIONS,
          placeholder: 'Select your language',
          onSelect: handleSelect,
          accentColor: config?.colors?.primary,
          selectedValue: findLanguage()
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.BorderedContainer, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.Label, {
          children: "About"
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.LabelData, {
          children: modalUser?.description && modalUser?.description?.length > 4 ? modalUser.description : 'No description'
        })]
      }), selectedUser && !config?.disableMemberProfileActions && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
        children: [!config?.hideMemberSendMessageAction && /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.ActionButton, {
          StartIcon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.ChatIcon, {}),
          onPress: handlePrivateMessage,
          variant: "filled",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
            style: {
              color: '#ffffff'
            },
            children: "Message"
          })
        }), !config?.hideMemberCopyIdAction && /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.ActionButton, {
          onPress: () => {}
          // onPress={() => handleCopyClick(selectedUser.id)}
          ,
          variant: "filled",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
            style: {
              color: '#ffffff'
            },
            children: "Copy User Id"
          })
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.BorderedContainer, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.ScrollView, {
          style: {
            maxHeight: 400
          },
          showsVerticalScrollIndicator: true,
          nestedScrollEnabled: true,
          children: documents.map(doc => /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
            style: {
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: 24,
              backgroundColor: '#F3F6FC',
              marginBottom: 8,
              paddingVertical: 8,
              paddingHorizontal: 16,
              borderRadius: 8
            },
            children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
              style: {
                flexDirection: 'row',
                alignItems: 'center',
                gap: 24
              },
              children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
                children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.IconDoc, {})
              }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
                children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.Label, {
                  style: {
                    paddingBottom: 4
                  },
                  children: doc.documentName
                }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.LabelData, {
                  children: new Date(doc.createdAt).toLocaleDateString('en-GB', {
                    day: '2-digit',
                    month: 'short',
                    year: 'numeric'
                  }) + ' ' + new Date(doc.createdAt).toLocaleTimeString('en-GB', {
                    hour: '2-digit',
                    minute: '2-digit'
                  })
                })]
              })]
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
              onPress: () => showDeleteModal(doc._id),
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.DeleteIcon, {})
            })]
          }, doc._id))
        })
      })]
    })]
  }), [modalUser, documents]);
  const EditingBody = (0, _react.useMemo)(() => /*#__PURE__*/(0, _jsxRuntime.jsx)(_EditUserModal.default, {
    setIsEditing: setIsEditing,
    modalUser: modalUser,
    config: config
  }), [modalUser]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.ModalContainerFullScreen, {
      children: !isEditing ? DefaultBody : EditingBody
    }), showDelete && /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.ModalBackground, {
      style: {
        position: 'absolute',
        zIndex: 9999
      },
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.ModalContainer, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.CloseButton, {
          onPress: () => setShowDelete(false),
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
            style: {
              fontSize: 24
            },
            children: "\xD7"
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.ModalTitle, {
          children: "Delete this document?"
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.GroupContainer, {
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
            onPress: () => setShowDelete(false),
            text: 'Cancel',
            style: {
              width: '100%'
            },
            unstyled: true,
            variant: "filled",
            color: "white"
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
            onPress: handleDeleteDocument,
            text: 'Delete',
            style: {
              width: '100%',
              borderWidth: 1,
              borderColor: 'red'
            },
            color: "red",
            unstyled: true,
            variant: "outlined"
          })]
        })]
      })
    })]
  });
};
var _default = exports.default = UserProfileModal;
//# sourceMappingURL=UserProfileModal.js.map