"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _styledModalComponents = require("../styledModalComponents");
var _reactNative = require("react-native");
var _ModalHeaderComponent = _interopRequireDefault(require("../ModalHeaderComponent"));
var _ProfileImagePlaceholder = require("../../MainComponents/ProfileImagePlaceholder");
var _reactRedux = require("react-redux");
var _roomStore = require("../../../roomStore");
var _auth = require("../../../networking/api-requests/auth.api");
var _xmppProvider = require("../../../context/xmppProvider");
var _roomsSlice = require("../../../roomStore/roomsSlice");
var ImagePicker = _interopRequireWildcard(require("expo-image-picker"));
var _Loader = _interopRequireDefault(require("../../styled/Loader"));
var _Button = _interopRequireDefault(require("../../styled/Button"));
var _icons = require("../../../assets/icons");
var _useChatSettingState = require("../../../hooks/useChatSettingState");
var _rooms = require("../../../networking/api-requests/rooms.api");
var _chatSettingsSlice = require("../../../roomStore/chatSettingsSlice");
var _MODAL_TYPES = require("../../../helpers/constants/MODAL_TYPES");
var _DropdownMenu = _interopRequireDefault(require("../../DropdownMenu/DropdownMenu"));
var _SelectUsersModal = _interopRequireDefault(require("../SelectUsersModal/SelectUsersModal"));
var _ToastContext = require("../../../context/ToastContext");
var _DeleteChatModal = _interopRequireDefault(require("./DeleteChatModal"));
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 ChatProfileModal = ({
  handleCloseModal
}) => {
  const [loading, setLoading] = (0, _react.useState)(false);
  const [visible, setVisible] = (0, _react.useState)(false);
  const [isModalOpen, setIsModalOpen] = (0, _react.useState)(false);
  const {
    showToast
  } = (0, _ToastContext.useToast)();
  const chatMenuOptions = (0, _react.useMemo)(() => [{
    label: 'Delete chat',
    icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.DeleteIcon, {}),
    onClick: () => {
      setIsModalOpen(true);
    },
    styles: {
      color: 'red'
    }
  }], []);
  const dispatch = (0, _reactRedux.useDispatch)();
  const {
    client
  } = (0, _xmppProvider.useXmppClient)();
  const {
    user: stateUser,
    config
  } = (0, _useChatSettingState.useChatSettingState)();
  const activeRoom = (0, _reactRedux.useSelector)(state => (0, _roomStore.getActiveRoom)(state));

  // Pull live member list from the MUC when the modal opens — REST
  // hydration only fills the *count* (item.participants /
  // item.members.length); the actual roster comes from a `getRoomMembers`
  // IQ which onGetMembers in stanzaHandlers parses into `roomMembers`.
  (0, _react.useEffect)(() => {
    if (client && activeRoom?.jid) {
      try {
        client.getRoomMembersStanza?.(activeRoom.jid);
      } catch {
        /* non-fatal */
      }
    }
  }, [client, activeRoom?.jid]);
  const onUpload = async () => {
    let loadingSet = false;
    try {
      setLoading(true);
      loadingSet = true;

      // expo-image-picker owns the permission prompt internally and
      // returns a `granted` flag. No separate react-native-permissions
      // round-trip needed.
      const perm = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (!perm.granted) {
        _reactNative.Alert.alert('Permission required', 'Photo library permission is needed to select images.', [{
          text: 'Cancel',
          onPress: () => setLoading(false),
          style: 'cancel'
        }, {
          text: 'Open Settings',
          onPress: () => _reactNative.Linking.openSettings()
        }]);
        return;
      }
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ['images'],
        allowsEditing: true,
        aspect: [1, 1],
        quality: 0.8
      });
      if (result.canceled || !result.assets?.[0]) {
        return;
      }
      const asset = result.assets[0];
      const originalName = asset.fileName || asset.uri.split('/').pop();
      const fileObject = {
        uri: asset.uri,
        type: asset.mimeType || 'image/jpeg',
        name: originalName || `profile_${Date.now()}.jpg`
      };
      const mediaData = new FormData();
      mediaData.append('files', fileObject);
      const uploadResult = await (0, _auth.uploadFile)(mediaData);
      const location = uploadResult?.data?.results?.[0]?.location;
      if (location) {
        client?.setRoomImageStanza(activeRoom?.jid || '', location, 'icon', 'none');
        dispatch((0, _roomsSlice.updateRoom)({
          jid: activeRoom?.jid || '',
          updates: {
            icon: location
          }
        }));
        showToast({
          id: Date.now().toString(),
          title: 'Success',
          message: 'Room image updated successfully',
          type: 'success'
        });
      }
    } catch (error) {
      if (error?.code === 'E_PICKER_CANCELLED' || error?.code === 'E_NO_CAMERA_PERMISSION') {
        console.log('User cancelled image selection');
        return;
      }
      console.error('File upload failed or location is missing:', error);
      showToast({
        id: Date.now().toString(),
        title: 'Error',
        message: 'Failed to upload image',
        type: 'error'
      });
    } finally {
      if (loadingSet) {
        setLoading(false);
      }
    }
  };
  const handleDeleteUser = async userId => {
    try {
      await (0, _rooms.deleteRoomMember)({
        roomId: activeRoom?.jid?.split('@')[0] || '',
        members: [userId]
      });
      dispatch((0, _roomsSlice.updateRoom)({
        jid: activeRoom?.jid || '',
        updates: {
          roomMembers: activeRoom?.roomMembers?.filter(user => user.xmppUsername !== userId)
        }
      }));
      showToast({
        id: Date.now().toString(),
        title: 'Success',
        message: `${userId} has been removed from the room.`,
        type: 'success'
      });
    } catch (error) {
      console.error('Failed to delete user:', error);
      showToast({
        id: Date.now().toString(),
        title: 'Error',
        message: 'Failed to delete user.',
        type: 'error'
      });
    }
  };
  const onRemoveClick = async () => {
    client?.setRoomImageStanza(activeRoom?.jid || '', '', 'icon', 'none');
    dispatch((0, _roomsSlice.updateRoom)({
      jid: activeRoom?.jid || '',
      updates: {
        icon: null
      }
    }));
  };
  const handleUserAvatarClick = user => {
    dispatch((0, _chatSettingsSlice.setActiveModal)(_MODAL_TYPES.MODAL_TYPES.PROFILE));
    dispatch((0, _chatSettingsSlice.setSelectedUser)({
      id: user._id,
      firstName: user.firstName,
      lastName: user.lastName,
      name: `${user.firstName} ${user.lastName}`,
      userJID: user?.xmppUsername,
      token: '',
      refreshToken: ''
    }));
  };
  const menuOptions = (0, _react.useMemo)(() => userId => [{
    label: 'Appoint as an admin',
    icon: null,
    onClick: () => {
      dispatch((0, _chatSettingsSlice.setActiveModal)(_MODAL_TYPES.MODAL_TYPES.PROFILE));
      console.log('Profile clicked');
    }
  }, {
    label: 'Unban',
    icon: null,
    onClick: () => {
      dispatch((0, _chatSettingsSlice.setActiveModal)(_MODAL_TYPES.MODAL_TYPES.SETTINGS));
      console.log('Settings clicked');
    }
  }, {
    label: 'Delete',
    icon: null,
    onClick: e => {
      e?.preventDefault();
      handleDeleteUser(userId);
    }
  }], []);
  (0, _react.useEffect)(() => {
    if (!activeRoom) {
      dispatch((0, _chatSettingsSlice.setActiveModal)(undefined));
    }
  }, [activeRoom, dispatch]);
  if (!activeRoom) {
    return null;
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.ModalContainerFullScreen, {
    style: {
      position: 'relative'
    },
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_ModalHeaderComponent.default, {
      handleCloseModal: handleCloseModal,
      headerTitle: 'Chat Profile',
      rightMenu: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
        children: [activeRoom?.type === 'public' && /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
          EndIcon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.QrIcon, {}),
          onPress: () => setVisible(true)
        }), activeRoom.role === 'moderator' && activeRoom.type !== 'private' && /*#__PURE__*/(0, _jsxRuntime.jsx)(_DropdownMenu.default, {
          position: "right",
          options: chatMenuOptions,
          openButton: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
            style: {
              padding: 8,
              height: 40
            },
            EndIcon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.MoreIcon, {}),
            unstyled: true
          })
        })]
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.CenterContainer, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_ProfileImagePlaceholder.ProfileImagePlaceholder, {
        name: activeRoom.title || activeRoom.name,
        icon: activeRoom.icon,
        upload: {
          onUpload,
          active: activeRoom?.role !== 'participant' ? true : false
        },
        remove: {
          enabled: true,
          onRemoveClick
        },
        role: activeRoom?.role,
        size: 128
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.UserInfo, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.UserName, {
          children: activeRoom.title || activeRoom.name
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.UserStatus, {
          children: [activeRoom.usersCnt, ' ', activeRoom.usersCnt > 1 ? 'members' : 'member']
        })]
      }), activeRoom.role === 'moderator' && activeRoom.type === 'group' && /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_SelectUsersModal.default, {})
      }), !config?.disableChatInfo?.disableDescription && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.BorderedContainer, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.LabelData, {
          children: "Description"
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.Label, {
          children: activeRoom?.description || '—'
        })]
      }), !config?.disableChatInfo?.disableType && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.BorderedContainer, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.LabelData, {
          children: "Chat type"
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.Label, {
          children: activeRoom.type || '—'
        })]
      }), !config?.disableChatInfo?.hideMembers && /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.BorderedContainer, {
        style: {
          paddingHorizontal: 16,
          paddingVertical: 8
        },
        children: loading ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Loader.default, {}) : (activeRoom?.roomMembers?.length ?? 0) === 0 ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.Label, {
          style: {
            opacity: 0.6,
            textAlign: 'center',
            paddingVertical: 8
          },
          children: "Member list unavailable"
        }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.ScrollView, {
          style: {
            maxHeight: 400
          },
          showsVerticalScrollIndicator: true,
          nestedScrollEnabled: true,
          children: activeRoom?.roomMembers?.map((user, index) => /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
            style: {
              flexDirection: 'column',
              alignItems: 'flex-start'
            },
            children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
              style: {
                flexDirection: 'row',
                justifyContent: 'flex-start',
                paddingHorizontal: 8,
                paddingVertical: 0,
                alignItems: 'center',
                width: '100%'
              },
              children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.Pressable, {
                style: {
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'flex-start',
                  gap: 16
                },
                onPress: () => handleUserAvatarClick(user),
                children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_ProfileImagePlaceholder.ProfileImagePlaceholder, {
                  name: `${user.firstName} ${user.lastName}`,
                  size: 40
                }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
                  style: {
                    flexDirection: 'column',
                    gap: 2,
                    alignItems: 'flex-start',
                    justifyContent: 'center'
                  },
                  children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.Label, {
                    style: {
                      fontSize: 16,
                      fontWeight: 600
                    },
                    children: [user.firstName, " ", user.lastName]
                  }), user.last_active && /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.LabelData, {
                    children: new Date(user.last_active * 1000).toLocaleString()
                  })]
                })]
              }), user.role && user.role !== 'none' && /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
                style: {
                  backgroundColor: user.ban_status !== 'banned' ? '#F3F6FC' : '#FFEBEE',
                  color: user.ban_status !== 'banned' ? '#0052CD' : '#F44336',
                  padding: 5,
                  borderRadius: 16,
                  fontSize: 12
                },
                children: user.role
              }), stateUser.xmppUsername !== user.xmppUsername && activeRoom.role === 'moderator' && activeRoom.type !== 'private' && /*#__PURE__*/(0, _jsxRuntime.jsx)(_DropdownMenu.default, {
                options: menuOptions(user.xmppUsername),
                openButton: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
                  onPress: () => {},
                  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
                    children: "More Options"
                  })
                }),
                onClose: () => console.log('Dropdown closed')
              })]
            }), index < (activeRoom?.roomMembers?.length || 0) - 1 && /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.Divider, {})]
          }, user.xmppUsername))
        })
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_DeleteChatModal.default, {
      isModalOpen: isModalOpen,
      setIsModalOpen: setIsModalOpen
    })]
  });
};
var _default = exports.default = ChatProfileModal;
//# sourceMappingURL=ChatProfileModal.js.map