import {
  Header_default
} from "./chunk-EZUCHTMK.mjs";
import {
  AddMembersDialog_default
} from "./chunk-6QJZZDGQ.mjs";
import {
  AddMembersMobile_default
} from "./chunk-S4A6TPVD.mjs";
import {
  DEFAULT_FORM_VALIDATION,
  getDefaultFormValues
} from "./chunk-SXJPBJ4C.mjs";
import {
  EditGroupTitleAndImage_default
} from "./chunk-3NQQRZFS.mjs";
import {
  GroupChatMembersList_default
} from "./chunk-PCNJUF7N.mjs";
import {
  CREATE_OR_EDIT_GROUP_FORM_VALUE
} from "./chunk-H5NG76GK.mjs";
import {
  useUpdateChatRoomMutation
} from "./chunk-VRKA22N5.mjs";
import {
  GroupDetailsQuery
} from "./chunk-MUWB4VY7.mjs";
import {
  useRoomListSubscription
} from "./chunk-QSPF5JY5.mjs";
import {
  MembersListFragment
} from "./chunk-ADJUUQ5O.mjs";
import {
  useGroupNameAndAvatar
} from "./chunk-2RPURWVV.mjs";

// tmp-babel/messages/web/GroupChatEdit/index.js
import { useMemo, useState, useTransition } from "react";
import { useCurrentProfile } from "@baseapp-frontend/authentication";
import { useResponsive } from "@baseapp-frontend/design-system/hooks/web";
import { filterDirtyValues, setFormRelayErrors, useNotification } from "@baseapp-frontend/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { Box } from "@mui/material";
import { useForm } from "react-hook-form";
import { usePaginationFragment, usePreloadedQuery } from "react-relay";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
function _typeof(o) {
  "@babel/helpers - typeof";
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof(o);
}
function ownKeys(e, r) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function(r2) {
      return Object.getOwnPropertyDescriptor(e, r2).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys(Object(t), true).forEach(function(r2) {
      _defineProperty(e, r2, t[r2]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
      Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
    });
  }
  return e;
}
function _defineProperty(e, r, t) {
  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e;
}
function _toPropertyKey(t) {
  var i = _toPrimitive(t, "string");
  return "symbol" == _typeof(i) ? i : i + "";
}
function _toPrimitive(t, r) {
  if ("object" != _typeof(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r || "default");
    if ("object" != _typeof(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r ? String : Number)(t);
}
function _slicedToArray(r, e) {
  return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(r, a) {
  if (r) {
    if ("string" == typeof r) return _arrayLikeToArray(r, a);
    var t = {}.toString.call(r).slice(8, -1);
    return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  }
}
function _arrayLikeToArray(r, a) {
  (null == a || a > r.length) && (a = r.length);
  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  return n;
}
function _iterableToArrayLimit(r, l) {
  var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (null != t) {
    var e, n, i, u, a = [], f = true, o = false;
    try {
      if (i = (t = t.call(r)).next, 0 === l) {
        if (Object(t) !== t) return;
        f = false;
      } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = true) ;
    } catch (r2) {
      o = true, n = r2;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a;
  }
}
function _arrayWithHoles(r) {
  if (Array.isArray(r)) return r;
}
var GroupChatEdit = function GroupChatEdit2(_ref) {
  var _GroupChatMembersList;
  var allProfilesRef = _ref.allProfilesRef, _ref$Header = _ref.Header, Header = _ref$Header === void 0 ? Header_default : _ref$Header, _ref$HeaderProps = _ref.HeaderProps, HeaderProps = _ref$HeaderProps === void 0 ? {} : _ref$HeaderProps, _ref$GroupChatMembers = _ref.GroupChatMembersList, GroupChatMembersList = _ref$GroupChatMembers === void 0 ? GroupChatMembersList_default : _ref$GroupChatMembers, _ref$GroupChatMembers2 = _ref.GroupChatMembersListProps, GroupChatMembersListProps = _ref$GroupChatMembers2 === void 0 ? {} : _ref$GroupChatMembers2, onCancellation = _ref.onCancellation, onRemovalFromGroup = _ref.onRemovalFromGroup, onValidSubmission = _ref.onValidSubmission, profileId = _ref.profileId, queryRef = _ref.queryRef, roomId = _ref.roomId;
  var _useNotification = useNotification(), sendToast = _useNotification.sendToast;
  var _useState = useState(false), _useState2 = _slicedToArray(_useState, 2), open = _useState2[0], setOpen = _useState2[1];
  var smDown = useResponsive("down", "sm");
  var _usePreloadedQuery = usePreloadedQuery(GroupDetailsQuery, queryRef), group = _usePreloadedQuery.chatRoom;
  var _useGroupNameAndAvata = useGroupNameAndAvatar(group), avatar = _useGroupNameAndAvata.avatar, title = _useGroupNameAndAvata.title;
  useRoomListSubscription({
    profileId,
    connections: [],
    onRemoval: onRemovalFromGroup
  });
  var _usePaginationFragmen = usePaginationFragment(MembersListFragment, group), membersList = _usePaginationFragmen.data, loadNext = _usePaginationFragmen.loadNext, isLoadingNext = _usePaginationFragmen.isLoadingNext, hasNext = _usePaginationFragmen.hasNext, refetch = _usePaginationFragmen.refetch;
  var participants = useMemo(function() {
    var _membersList$particip;
    return membersList === null || membersList === void 0 || (_membersList$particip = membersList.participants) === null || _membersList$particip === void 0 || (_membersList$particip = _membersList$particip.edges) === null || _membersList$particip === void 0 ? void 0 : _membersList$particip.map(function(edge) {
      var _edge$node;
      return (edge === null || edge === void 0 || (_edge$node = edge.node) === null || _edge$node === void 0 ? void 0 : _edge$node.profile) && edge.node.profile;
    });
  }, [membersList]);
  var formReturn = useForm({
    defaultValues: getDefaultFormValues(title || "", avatar),
    resolver: zodResolver(DEFAULT_FORM_VALIDATION),
    mode: "onBlur"
  });
  var setValue = formReturn.setValue, watch = formReturn.watch, handleSubmit = formReturn.handleSubmit, _formReturn$formState = formReturn.formState, isValid = _formReturn$formState.isValid, isDirty = _formReturn$formState.isDirty, dirtyFields = _formReturn$formState.dirtyFields;
  var _useUpdateChatRoomMut = useUpdateChatRoomMutation(), _useUpdateChatRoomMut2 = _slicedToArray(_useUpdateChatRoomMut, 2), commit = _useUpdateChatRoomMut2[0], isMutationInFlight = _useUpdateChatRoomMut2[1];
  var onSubmit = handleSubmit(function(data) {
    if (!roomId) return;
    var dirtyValues = filterDirtyValues({
      values: data,
      dirtyFields
    });
    var image = data.image;
    var uploadables = {};
    if ("image" in dirtyValues) {
      if (image && (image instanceof File || image instanceof Blob)) {
        uploadables.image = image;
      } else {
        dirtyValues.deleteImage = true;
      }
      delete dirtyValues.image;
    }
    delete dirtyValues.participants;
    commit({
      variables: {
        input: _objectSpread({
          roomId,
          profileId
        }, dirtyValues),
        connections: []
      },
      uploadables,
      onCompleted: function onCompleted(response) {
        var _response$chatRoomUpd;
        var errors = response === null || response === void 0 || (_response$chatRoomUpd = response.chatRoomUpdate) === null || _response$chatRoomUpd === void 0 ? void 0 : _response$chatRoomUpd.errors;
        if (errors) {
          sendToast("Something went wrong", {
            type: "error"
          });
          setFormRelayErrors(formReturn, errors);
        } else {
          onValidSubmission();
        }
      }
    });
  });
  var isEditButtonDisabled = !isValid || !isDirty;
  var _useTransition = useTransition(), _useTransition2 = _slicedToArray(_useTransition, 2), isPending = _useTransition2[0], startTransition = _useTransition2[1];
  var handleAddMemberSuccess = function handleAddMemberSuccess2() {
    setOpen(false);
    startTransition(function() {
      refetch === null || refetch === void 0 || refetch({});
    });
  };
  if (smDown && open) return /* @__PURE__ */ _jsx(AddMembersMobile_default, {
    allProfilesRef,
    onClose: function onClose() {
      return setOpen(false);
    },
    handleSubmitSuccess: handleAddMemberSuccess,
    profileId,
    roomId,
    isPending,
    existingMembers: participants
  });
  return /* @__PURE__ */ _jsxs(Box, {
    children: [/* @__PURE__ */ _jsx(AddMembersDialog_default, {
      open,
      allProfilesRef,
      onClose: function onClose() {
        return setOpen(false);
      },
      handleSubmitSuccess: handleAddMemberSuccess,
      profileId,
      roomId,
      isPending,
      existingMembers: participants
    }), /* @__PURE__ */ _jsx(Header, _objectSpread({
      isEditButtonDisabled,
      isMutationInFlight,
      onCancellation,
      onSubmit
    }, HeaderProps)), /* @__PURE__ */ _jsx(EditGroupTitleAndImage_default, {
      form: formReturn,
      FORM_VALUE: CREATE_OR_EDIT_GROUP_FORM_VALUE,
      isMutationInFlight
    }), /* @__PURE__ */ _jsx(GroupChatMembersList, _objectSpread({
      FORM_VALUE: CREATE_OR_EDIT_GROUP_FORM_VALUE,
      setValue,
      watch,
      currentParticipants: participants,
      refetch,
      membersLoadNext: loadNext,
      membersHasNext: hasNext,
      membersIsLoadingNext: isLoadingNext,
      MembersListProps: _objectSpread({
        allowAddMember: true,
        onAddMemberClick: function onAddMemberClick() {
          return setOpen(true);
        }
      }, (_GroupChatMembersList = GroupChatMembersListProps === null || GroupChatMembersListProps === void 0 ? void 0 : GroupChatMembersListProps.MembersListProps) !== null && _GroupChatMembersList !== void 0 ? _GroupChatMembersList : {})
    }, GroupChatMembersListProps))]
  });
};
var WrappedEditGroup = function WrappedEditGroup2(props) {
  var _useCurrentProfile = useCurrentProfile(), currentProfile = _useCurrentProfile.currentProfile;
  if (!(currentProfile !== null && currentProfile !== void 0 && currentProfile.id)) {
    return null;
  }
  return /* @__PURE__ */ _jsx(GroupChatEdit, _objectSpread({
    profileId: currentProfile.id
  }, props));
};
var GroupChatEdit_default = WrappedEditGroup;

export {
  GroupChatEdit_default
};
//# sourceMappingURL=chunk-G3KYO4FL.mjs.map