"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _Button = _interopRequireDefault(require("../../styled/Button"));
var _icons = require("../../../assets/icons");
var _xmppProvider = require("../../../context/xmppProvider");
var _styledModalComponents = require("../styledModalComponents");
var _roomsSlice = require("../../../roomStore/roomsSlice");
var _StyledInput = _interopRequireDefault(require("../../styled/StyledInput"));
var _auth = require("../../../networking/api-requests/auth.api");
var _ProfileImagePlaceholder = require("../../MainComponents/ProfileImagePlaceholder");
var _reactNative = require("react-native");
var ImagePicker = _interopRequireWildcard(require("expo-image-picker"));
var _createRoomFromApi = require("../../../helpers/createRoomFromApi");
var _rooms = require("../../../networking/api-requests/rooms.api");
var _hooks = require("../../../hooks/hooks");
var _useChatSettingState = require("../../../hooks/useChatSettingState");
var _ToastContext = require("../../../context/ToastContext");
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 NewChatModal = ({
  // Some call sites mount `<NewChatModal />` with no props (e.g. the
  // empty-state in ChatRoom when roomsList is empty). Default to a noop
  // so the Close/Cancel buttons don't throw "handleClose is not a
  // function".
  handleCloseModal: handleClose = () => {}
}) => {
  const config = (0, _hooks.useAppSelector)(state => state.chatSettingStore.config);
  const dispatch = (0, _hooks.useAppDispatch)();
  const {
    client
  } = (0, _xmppProvider.useXmppClient)();
  const {
    user
  } = (0, _useChatSettingState.useChatSettingState)();
  const {
    showToast
  } = (0, _ToastContext.useToast)();
  const [isModalOpen, setIsModalOpen] = (0, _react.useState)(false);
  const [loading, setLoading] = (0, _react.useState)(false);
  const [activeTab, setActiveTab] = (0, _react.useState)('0');
  const [roomName, setRoomName] = (0, _react.useState)('');
  const [roomDescription, setRoomDescription] = (0, _react.useState)('');
  const [chatType, setChatType] = (0, _react.useState)({
    name: 'Public',
    id: 'public'
  });
  const [profileImage, setProfileImage] = (0, _react.useState)(null);
  const [errors, setErrors] = (0, _react.useState)({
    name: '',
    description: ''
  });
  const [selectedUsers, setSelectedUsers] = (0, _react.useState)([]);
  const isValid = (0, _react.useMemo)(
  // () => roomName.length >= 3 && roomDescription.length >= 5,
  () => roomName.length >= 3, [roomName, roomDescription]);
  const validateRoomName = name => {
    if (name.trim().length < 3) {
      return 'Room name must be at least 3 characters.';
    }
    return '';
  };

  // const validateRoomDescription = (description: string) => {
  //   if (description.trim().length < 5) {
  //     return 'Room description must be at least 5 characters.';
  //   }
  //   return '';
  // };

  const handleRoomNameChange = e => {
    const name = e;
    setRoomName(name);
    setErrors(prevErrors => ({
      ...prevErrors,
      name: validateRoomName(name)
    }));
  };
  const handleRoomDescriptionChange = e => {
    const description = e;
    setRoomDescription(description);
    setErrors(prevErrors => ({
      ...prevErrors
      // description: validateRoomDescription(description),
    }));
  };
  const handleOpenModal = () => setIsModalOpen(true);
  const handleCloseModal = () => {
    handleClose();
    setActiveTab('0');
    setIsModalOpen(false);
    setRoomName('');
    setSelectedUsers([]);
  };
  const onUpload = async () => {
    try {
      const {
        status
      } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== 'granted') {
        _reactNative.Alert.alert('Permission required', 'Photo library permission is needed to select images.', [{
          text: 'Cancel',
          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) return;
      const asset = result.assets[0];
      const originalName = asset.uri.split('/').pop();
      const fileObject = {
        uri: asset.uri,
        type: asset.mimeType || 'image/jpeg',
        name: originalName || `profile_${Date.now()}.jpg`
      };
      setProfileImage(fileObject);
    } catch (error) {
      console.error('Image selection failed:', error);
      _reactNative.Alert.alert('Error', 'Failed to select image');
    }
  };
  const onRemoveClick = async () => {
    setProfileImage(null);
  };
  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 successfully',
        type: 'success'
      });
    } catch (error) {
      console.error('Error handling room creation:', error);
      showToast({
        id: Date.now().toString(),
        title: 'Error',
        message: 'Failed to create room',
        type: 'error'
      });
    }
  };
  const handleCreateRoom = async () => {
    setLoading(true);
    if (isValid) {
      let location;
      if (profileImage && typeof profileImage === 'object' && 'uri' in profileImage) {
        try {
          const mediaData = new FormData();
          mediaData.append('files', profileImage);
          const uploadResult = await (0, _auth.uploadFile)(mediaData);
          location = uploadResult?.data?.results?.[0]?.location;
        } catch (error) {
          console.error('Failed to upload image:', error);
          setLoading(false);
          return;
        }
      }
      if (config?.newArch) {
        const namesArray = selectedUsers.map(user => user.xmppUsername);
        const newChat = await (0, _rooms.postRoom)({
          title: roomName,
          description: roomDescription && roomDescription !== '' ? roomDescription : 'No description',
          picture: location || '',
          type: chatType.id || 'public',
          members: namesArray
        });
        handleRoomCreation(newChat, namesArray.length);
        handleCloseModal();
      } else {
        try {
          const newChatJid = await client?.createRoomStanza(roomName, roomDescription && roomDescription !== '' ? roomDescription : 'No description');
          const jidStr = typeof newChatJid === 'string' ? newChatJid : '';
          client?.getRoomsStanza();
          dispatch((0, _roomsSlice.setCurrentRoom)({
            roomJID: jidStr
          }));
          if (location) {
            client?.setRoomImageStanza(jidStr, location, 'icon', 'none');
            dispatch((0, _roomsSlice.updateRoom)({
              jid: jidStr,
              updates: {
                icon: location
              }
            }));
          }
          showToast({
            id: Date.now().toString(),
            title: 'Success',
            message: 'Room created successfully',
            type: 'success'
          });
          handleCloseModal();
        } catch (error) {
          console.error('Failed to create room:', error);
          showToast({
            id: Date.now().toString(),
            title: 'Error',
            message: 'Failed to create room',
            type: 'error'
          });
        }
      }
      setIsModalOpen(false);
      setErrors({
        name: '',
        description: ''
      });
      setProfileImage(null);
      setRoomName('');
      setRoomDescription('');
      setLoading(false);
    }
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.ModalBackground
    // visible={isModalOpen}
    // transparent={true}
    // animationType="fade"
    // onRequestClose={handleCloseModal}
    , {
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.ModalContainer, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.CloseButton, {
          onPress: handleCloseModal,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
            style: {
              fontSize: 24,
              padding: 5
            },
            children: "\xD7"
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledModalComponents.ModalTitle, {
          children: "Create New Chat"
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_ProfileImagePlaceholder.ProfileImagePlaceholder, {
          size: 120,
          upload: {
            active: true,
            onUpload
          },
          remove: {
            enabled: true,
            onRemoveClick
          },
          placeholderIcon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.AddPhotoIcon, {
            color: "#0052CD"
          }),
          icon: profileImage && typeof profileImage === 'object' && 'uri' in profileImage ? {
            uri: profileImage.uri
          } : profileImage,
          disableOverlay: !profileImage,
          role: "user"
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.GroupContainer, {
          style: {
            flexDirection: 'column',
            position: 'relative',
            width: '100%'
          },
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_StyledInput.default, {
            color: "#F5F7F9",
            id: "roomName",
            value: roomName,
            onChangeText: handleRoomNameChange,
            placeholder: "Enter Room Name",
            helperText: errors.name,
            error: !!errors.name
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_StyledInput.default, {
            color: "#F5F7F9",
            id: "roomDescription",
            value: roomDescription,
            onChangeText: handleRoomDescriptionChange,
            placeholder: "Enter Description",
            helperText: errors.description,
            error: !!errors.description
          })]
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styledModalComponents.GroupContainer, {
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
            onPress: handleCreateRoom,
            text: 'Create',
            style: {
              width: '100%'
            },
            unstyled: true,
            variant: "filled",
            disabled: !isValid,
            color: "#fff"
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
            onPress: handleCloseModal,
            text: 'Cancel',
            style: {
              width: '100%'
            },
            unstyled: true,
            variant: "outlined",
            color: "#0052CD"
          })]
        })]
      })
    })
  });
};
var _default = exports.default = NewChatModal;
//# sourceMappingURL=NewChatModal.js.map