import {
  ChatRoomItem_default
} from "./chunk-VW5XMEJA.mjs";
import {
  EmptyChatRoomsState_default
} from "./chunk-HTTHHBA5.mjs";
import {
  CHAT_TAB_LABEL,
  CHAT_TAB_VALUES
} from "./chunk-VIDLBR2A.mjs";
import {
  Header,
  MainContainer
} from "./chunk-H74U2VIA.mjs";
import {
  useRoomListSubscription
} from "./chunk-QSPF5JY5.mjs";
import {
  useRoomsList
} from "./chunk-ESY3D4EX.mjs";
import {
  useChatRoom_default
} from "./chunk-U2XGYM5M.mjs";
import {
  SearchNotFoundState_default
} from "./chunk-O6DYR43U.mjs";

// tmp-babel/messages/web/AllChatRoomsList/index.js
import { useCallback, useEffect, useMemo, useState, useTransition } from "react";
import { LoadingState } from "@baseapp-frontend/design-system/components/web/displays";
import { Iconify } from "@baseapp-frontend/design-system/components/web/images";
import { Searchbar as DefaultSearchbar } from "@baseapp-frontend/design-system/components/web/inputs";
import { Box, Button, CircularProgress, Tab, Tabs, Typography } from "@mui/material";
import { useForm } from "react-hook-form";
import { Virtuoso } from "react-virtuoso";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } 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 AllChatRoomsList = function AllChatRoomsList2(_ref) {
  var _targetRef$me, _data$chatRooms2;
  var targetRef = _ref.targetRef, _ref$onHeaderClick = _ref.onHeaderClick, onHeaderClick = _ref$onHeaderClick === void 0 ? function() {
  } : _ref$onHeaderClick, _ref$Searchbar = _ref.Searchbar, Searchbar = _ref$Searchbar === void 0 ? DefaultSearchbar : _ref$Searchbar, _ref$SearchbarProps = _ref.SearchbarProps, SearchbarProps = _ref$SearchbarProps === void 0 ? {} : _ref$SearchbarProps, _ref$ChatRoomItem = _ref.ChatRoomItem, ChatRoomItem = _ref$ChatRoomItem === void 0 ? ChatRoomItem_default : _ref$ChatRoomItem, _ref$ChatRoomItemProp = _ref.ChatRoomItemProps, ChatRoomItemProps = _ref$ChatRoomItemProp === void 0 ? {} : _ref$ChatRoomItemProp, _ref$EmptyChatRoomsSt = _ref.EmptyChatRoomsState, EmptyChatRoomsState = _ref$EmptyChatRoomsSt === void 0 ? EmptyChatRoomsState_default : _ref$EmptyChatRoomsSt, _ref$VirtuosoProps = _ref.VirtuosoProps, VirtuosoProps = _ref$VirtuosoProps === void 0 ? {} : _ref$VirtuosoProps;
  var _useState = useState(CHAT_TAB_VALUES.active), _useState2 = _slicedToArray(_useState, 2), tab = _useState2[0], setTab = _useState2[1];
  var _useState3 = useState(true), _useState4 = _slicedToArray(_useState3, 2), renderList = _useState4[0], setRenderList = _useState4[1];
  var _useTransition = useTransition(), _useTransition2 = _slicedToArray(_useTransition, 2), isRefetchPending = _useTransition2[0], startRefetchTransition = _useTransition2[1];
  var _useRoomsList = useRoomsList(targetRef === null || targetRef === void 0 || (_targetRef$me = targetRef.me) === null || _targetRef$me === void 0 ? void 0 : _targetRef$me.profile), data = _useRoomsList.data, loadNext = _useRoomsList.loadNext, isLoadingNext = _useRoomsList.isLoadingNext, hasNext = _useRoomsList.hasNext, refetch = _useRoomsList.refetch;
  var _useTransition3 = useTransition(), _useTransition4 = _slicedToArray(_useTransition3, 2), isPending = _useTransition4[0], startTransition = _useTransition4[1];
  var _useForm = useForm({
    defaultValues: {
      search: ""
    }
  }), control = _useForm.control, reset = _useForm.reset, watch = _useForm.watch;
  var isInArchivedTab = tab === CHAT_TAB_VALUES.archived;
  var isInUnreadTab = tab === CHAT_TAB_VALUES.unread;
  var searchValue = watch("search");
  var handleSearchChange = function handleSearchChange2(e) {
    var value = e.target.value || "";
    startTransition(function() {
      refetch({
        q: value,
        unreadMessages: isInUnreadTab,
        archived: isInArchivedTab
      }, {
        fetchPolicy: "network-only"
      });
    });
  };
  var handleSearchClear = function handleSearchClear2() {
    startTransition(function() {
      reset();
      refetch({
        q: "",
        unreadMessages: isInUnreadTab,
        archived: isInArchivedTab
      }, {
        fetchPolicy: "network-only"
      });
    });
  };
  var handleChange = function handleChange2(event, newTab) {
    setTab(newTab);
    startRefetchTransition(function() {
      setRenderList(false);
      refetch({
        q: searchValue,
        unreadMessages: newTab === CHAT_TAB_VALUES.unread,
        archived: newTab === CHAT_TAB_VALUES.archived
      }, {
        fetchPolicy: "network-only"
      });
    });
  };
  useEffect(function() {
    setRenderList(true);
  }, [data]);
  var _useChatRoom = useChatRoom_default(), selectedRoom = _useChatRoom.id, setChatRoom = _useChatRoom.setChatRoom;
  var chatRooms = useMemo(function() {
    var _data$chatRooms;
    return (data === null || data === void 0 || (_data$chatRooms = data.chatRooms) === null || _data$chatRooms === void 0 || (_data$chatRooms = _data$chatRooms.edges) === null || _data$chatRooms === void 0 ? void 0 : _data$chatRooms.filter(function(edge) {
      return edge === null || edge === void 0 ? void 0 : edge.node;
    }).map(function(edge) {
      return edge === null || edge === void 0 ? void 0 : edge.node;
    })) || [];
  }, [data === null || data === void 0 || (_data$chatRooms2 = data.chatRooms) === null || _data$chatRooms2 === void 0 ? void 0 : _data$chatRooms2.edges]);
  useRoomListSubscription({
    profileId: data.id,
    connections: []
  });
  var renderItem = useCallback(function(room) {
    if (!room) return null;
    return /* @__PURE__ */ _jsx(ChatRoomItem, _objectSpread({
      roomRef: room,
      isCardSelected: selectedRoom === room.id,
      handleClick: function handleClick() {
        setChatRoom({
          id: room.id
        });
      },
      isInArchivedTab
    }, ChatRoomItemProps));
  }, [selectedRoom, setChatRoom, ChatRoomItemProps, ChatRoomItem, isInArchivedTab]);
  var renderLoadingState = function renderLoadingState2() {
    if (!isLoadingNext) return /* @__PURE__ */ _jsx(Box, {
      sx: {
        paddingTop: 3
      }
    });
    return /* @__PURE__ */ _jsx(LoadingState, {
      sx: {
        paddingTop: 3,
        paddingBottom: 1
      },
      CircularProgressProps: {
        size: 15
      },
      "aria-label": "loading more rooms"
    });
  };
  var renderTabLabel = function renderTabLabel2(tabValue) {
    return /* @__PURE__ */ _jsxs(Box, {
      display: "grid",
      gap: 1,
      gridTemplateColumns: "1fr min-content",
      alignItems: "center",
      children: [/* @__PURE__ */ _jsx(Typography, {
        variant: "subtitle2",
        color: "text.primary",
        children: CHAT_TAB_LABEL[tabValue]
      }), isRefetchPending && tab === tabValue && /* @__PURE__ */ _jsx(CircularProgress, {
        size: 15
      })]
    });
  };
  var renderListContent = function renderListContent2() {
    var hasEmptyStates = !isPending && chatRooms.length === 0;
    if (hasEmptyStates) {
      if (searchValue) return /* @__PURE__ */ _jsx(SearchNotFoundState_default, {});
      return /* @__PURE__ */ _jsx(EmptyChatRoomsState, {});
    }
    return void 0;
  };
  return /* @__PURE__ */ _jsxs(_Fragment, {
    children: [/* @__PURE__ */ _jsx(Header, {
      children: /* @__PURE__ */ _jsxs(Box, {
        display: "grid",
        width: "100%",
        gridTemplateColumns: "auto min-content",
        gap: 1,
        children: [/* @__PURE__ */ _jsx(Typography, {
          variant: "h4",
          component: "span",
          children: "Messages"
        }), /* @__PURE__ */ _jsx(Button, {
          variant: "contained",
          color: "inherit",
          startIcon: /* @__PURE__ */ _jsx(Iconify, {
            icon: "mingcute:add-line"
          }),
          onClick: onHeaderClick,
          children: "New"
        })]
      })
    }), /* @__PURE__ */ _jsxs(MainContainer, {
      children: [/* @__PURE__ */ _jsx(Box, {
        sx: {
          paddingX: {
            xs: 1.5,
            sm: 2.5
          },
          paddingTop: 2
        },
        children: /* @__PURE__ */ _jsx(
          Searchbar,
          _objectSpread({
            name: "search",
            control,
            onChange: handleSearchChange,
            onClear: handleSearchClear,
            isPending
          }, SearchbarProps),
          tab
          /* The handleSearchChange function depends on tab.
          Searchbar calls useRef on the onChange function (to debounce),
          hence it does not see the changes unless it is reloaded */
        )
      }), /* @__PURE__ */ _jsxs(Tabs, {
        value: tab,
        onChange: handleChange,
        centered: true,
        variant: "fullWidth",
        sx: {
          paddingX: {
            xs: 0,
            sm: 2.5
          },
          paddingTop: 2
        },
        children: [/* @__PURE__ */ _jsx(Tab, {
          label: renderTabLabel(CHAT_TAB_VALUES.active),
          value: CHAT_TAB_VALUES.active
        }), /* @__PURE__ */ _jsx(Tab, {
          label: renderTabLabel(CHAT_TAB_VALUES.unread),
          value: CHAT_TAB_VALUES.unread
        }), /* @__PURE__ */ _jsx(Tab, {
          label: renderTabLabel(CHAT_TAB_VALUES.archived),
          value: CHAT_TAB_VALUES.archived
        })]
      }), renderListContent(), renderList && /* @__PURE__ */ _jsx(Virtuoso, _objectSpread({
        data: chatRooms,
        overscan: 1,
        itemContent: function itemContent(_index, item) {
          return renderItem(item);
        },
        style: {
          scrollbarWidth: "none"
        },
        components: {
          Footer: renderLoadingState
        },
        endReached: function endReached() {
          if (hasNext) {
            loadNext(5);
          }
        }
      }, VirtuosoProps))]
    })]
  });
};
var AllChatRoomsList_default = AllChatRoomsList;

export {
  AllChatRoomsList_default
};
//# sourceMappingURL=chunk-QHGXQ4CB.mjs.map