import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { useState, useEffect, useMemo, memo, useRef } from 'react';
import { withT, useOnClickOutside } from '@bigbinary/neeto-commons-frontend/react-utils';
import Dropdown from '@bigbinary/neetoui/Dropdown';
import { filter, prop } from 'ramda';
import { isNotEmpty, noop } from '@bigbinary/neeto-cist';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import Input from '@bigbinary/neetoui/Input';
import { useTranslation } from 'react-i18next';
import classnames from 'classnames';
import Typography from '@bigbinary/neetoui/Typography';
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
import RemoveCircle from '@bigbinary/neeto-icons/RemoveCircle';
import Button$1 from '@bigbinary/neetoui/Button';
import Tooltip from '@bigbinary/neetoui/Tooltip';
import Down from '@bigbinary/neeto-icons/Down';

var TABS = {
  TEAMS_TAB: "teams",
  MEMBERS_TAB: "members"
};

var SelectMember = withT(function (_ref) {
  var t = _ref.t,
    members = _ref.members,
    setMember = _ref.setMember,
    selectedMember = _ref.selectedMember,
    loadingMember = _ref.loadingMember;
  return /*#__PURE__*/jsx(Fragment, {
    children: isNotEmpty(members) ? members === null || members === void 0 ? void 0 : members.map(function (member) {
      return /*#__PURE__*/jsx("li", {
        "data-testid": "agent-options",
        className: classnames({
          active: selectedMember && selectedMember.value === member.value,
          loading: loadingMember && loadingMember === member.value
        }),
        onClick: function onClick(event) {
          event.preventDefault();
          if (!loadingMember) {
            setMember(member);
          }
        },
        children: /*#__PURE__*/jsx("span", {
          className: "truncate",
          children: member.label
        })
      }, member.value);
    }) : /*#__PURE__*/jsx("li", {
      className: "flex justify-center",
      children: /*#__PURE__*/jsx(Typography, {
        className: "px-3",
        children: t("neetoTeamMembers.helpers.noRecords")
      })
    })
  });
});

var SelectTeam = function SelectTeam(_ref) {
  var teams = _ref.teams,
    setTeam = _ref.setTeam,
    selectedTeam = _ref.selectedTeam,
    loadingTeam = _ref.loadingTeam;
  return /*#__PURE__*/jsx(Fragment, {
    children: teams === null || teams === void 0 ? void 0 : teams.map(function (group) {
      return /*#__PURE__*/jsx("li", {
        "data-testid": "group-options",
        className: classnames({
          active: selectedTeam && selectedTeam.value === group.value,
          loading: loadingTeam && loadingTeam === group.value
        }),
        onClick: function onClick(event) {
          event.preventDefault();
          if (!loadingTeam) {
            setTeam(group);
          }
        },
        children: group.label
      }, group.value);
    })
  });
};

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).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 (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var TabBody = function TabBody(_ref) {
  var selectedTab = _ref.selectedTab,
    teams = _ref.teams,
    teamTitle = _ref.teamTitle,
    members = _ref.members,
    setMember = _ref.setMember,
    setTeam = _ref.setTeam,
    selectedMember = _ref.selectedMember,
    selectedTeam = _ref.selectedTeam,
    loading = _ref.loading,
    memberTitle = _ref.memberTitle,
    showTeams = _ref.showTeams;
  var _useState = useState(""),
    _useState2 = _slicedToArray(_useState, 2),
    memberString = _useState2[0],
    setMemberString = _useState2[1];
  var _useState3 = useState(""),
    _useState4 = _slicedToArray(_useState3, 2),
    teamString = _useState4[0],
    setTeamString = _useState4[1];
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  useEffect(function () {
    setMemberString("");
  }, [selectedMember]);
  useEffect(function () {
    setTeamString("");
  }, [selectedTeam]);
  var filteredMembers = useMemo(function () {
    return members === null || members === void 0 ? void 0 : members.filter(function (member) {
      var _member$label;
      return ((_member$label = member.label) === null || _member$label === void 0 ? void 0 : _member$label.toLowerCase().indexOf(memberString.toLowerCase())) > -1;
    });
  }, [members, memberString]);
  var filteredTeams = useMemo(function () {
    return teams === null || teams === void 0 ? void 0 : teams.filter(function (team) {
      var _team$label;
      return ((_team$label = team.label) === null || _team$label === void 0 ? void 0 : _team$label.toLowerCase().indexOf(teamString.toLowerCase())) > -1;
    });
  }, [teams, teamString]);
  var teamInputProps = {
    value: teamString,
    placeholder: t("neetoTeamMembers.placeholders.searchEntity", {
      entity: teamTitle
    }),
    onChange: function onChange(event) {
      return setTeamString(event.target.value.trimStart());
    }
  };
  var memberInputProps = {
    value: memberString,
    placeholder: t("neetoTeamMembers.placeholders.searchEntity", {
      entity: memberTitle
    }),
    onChange: function onChange(event) {
      return setMemberString(event.target.value.trimStart());
    }
  };
  var isTeamTab = useMemo(function () {
    return selectedTab === TABS.TEAMS_TAB && showTeams;
  }, [selectedTab]);
  var inputProps = isTeamTab ? teamInputProps : memberInputProps;
  return /*#__PURE__*/jsxs(Fragment, {
    children: [/*#__PURE__*/jsx("div", {
      className: "px-4 py-2",
      children: /*#__PURE__*/jsx(Input, _objectSpread({}, inputProps))
    }), /*#__PURE__*/jsx("div", {
      className: "max-h-56 w-72 overflow-y-auto",
      children: isTeamTab ? /*#__PURE__*/jsx(SelectTeam, {
        selectedTeam: selectedTeam,
        setTeam: setTeam,
        loadingTeam: loading.team,
        teams: filteredTeams
      }) : /*#__PURE__*/jsx(SelectMember, {
        selectedMember: selectedMember,
        setMember: setMember,
        loadingMember: loading.member,
        members: filteredMembers
      })
    })]
  });
};

var Tab = withT(function (_ref) {
  var t = _ref.t,
    title = _ref.title,
    value = _ref.value,
    onClick = _ref.onClick,
    active = _ref.active,
    removeValue = _ref.removeValue,
    loading = _ref.loading;
  return /*#__PURE__*/jsx("div", {
    className: "w-1/2 cursor-pointer",
    children: /*#__PURE__*/jsxs("div", {
      onClick: onClick,
      className: classnames(["neeto-ui-text-gray-500 border-b-2 px-4 py-4"], {
        "neeto-ui-text-gray-600 neeto-ui-border-primary-500 neeto-ui-bg-white": active
      }),
      children: [/*#__PURE__*/jsx("div", {
        className: "neeto-ui-text-gray-800 mb-1.5 text-xs font-semibold uppercase tracking-wide",
        "data-testid": "select-group-or-agent",
        children: title
      }), /*#__PURE__*/jsxs("div", {
        className: "neeto-ui-text-gray-400 flex flex-row items-center justify-start text-sm font-normal",
        "data-testid": "ticket-table-assignee-or-group",
        children: [loading && /*#__PURE__*/jsx("span", {
          className: "bp3-skeleton flex justify-center",
          children: t("neetoTeamMembers.common.loading")
        }), !loading && (value ? /*#__PURE__*/jsxs(Fragment, {
          children: [/*#__PURE__*/jsx(Button$1, {
            className: "neeto-ui-text-error-600 shrink-0",
            icon: RemoveCircle,
            style: "text",
            onClick: removeValue
          }), /*#__PURE__*/jsx("span", {
            className: "neeto-ui-text-gray-800 ms-1 truncate font-medium",
            children: value
          })]
        }) : /*#__PURE__*/jsx("span", {
          className: "neeto-ui-text-gray-600 py-1.5",
          children: "--"
        }))]
      })]
    })
  });
});
var TabHeader = function TabHeader(_ref2) {
  var selectedTab = _ref2.selectedTab,
    setSelectedTab = _ref2.setSelectedTab,
    selectedMember = _ref2.selectedMember,
    selectedTeam = _ref2.selectedTeam,
    onClearMember = _ref2.onClearMember,
    onClearTeam = _ref2.onClearTeam,
    loading = _ref2.loading,
    showTeams = _ref2.showTeams,
    teamTitle = _ref2.teamTitle,
    memberTitle = _ref2.memberTitle;
  var teamTab = selectedTab === TABS.TEAMS_TAB;
  var memberTab = selectedTab === TABS.MEMBERS_TAB;
  return /*#__PURE__*/jsxs("div", {
    className: "neeto-ui-bg-gray-100 -mt-2 flex w-72 flex-row items-center justify-start",
    children: [showTeams && /*#__PURE__*/jsx(Tab, {
      active: teamTab,
      loading: !!loading.team,
      removeValue: onClearTeam,
      title: teamTitle,
      value: selectedTeam !== null && selectedTeam !== void 0 && selectedTeam.value ? selectedTeam.label : null,
      onClick: function onClick() {
        return setSelectedTab(TABS.TEAMS_TAB);
      }
    }), /*#__PURE__*/jsx(Tab, {
      active: memberTab,
      loading: !!loading.member,
      removeValue: onClearMember,
      title: memberTitle,
      value: selectedMember !== null && selectedMember !== void 0 && selectedMember.value ? selectedMember.label : null,
      onClick: function onClick() {
        return setSelectedTab(TABS.MEMBERS_TAB);
      }
    })]
  });
};

var DropDownContent = function DropDownContent(_ref) {
  var selectedMember = _ref.selectedMember,
    selectedTeam = _ref.selectedTeam,
    setSelectedTeam = _ref.setSelectedTeam,
    setSelectedMember = _ref.setSelectedMember,
    members = _ref.members,
    teams = _ref.teams,
    filterMembersBy = _ref.filterMembersBy,
    loading = _ref.loading,
    teamTitle = _ref.teamTitle,
    memberTitle = _ref.memberTitle;
  var _useState = useState(TABS.TEAMS_TAB),
    _useState2 = _slicedToArray(_useState, 2),
    selectedTab = _useState2[0],
    setSelectedTab = _useState2[1];
  var showTeams = useMemo(function () {
    return isNotEmpty(teams);
  }, [teams]);
  var handleSelectTeam = function handleSelectTeam(team) {
    setSelectedTeam(team);
    setSelectedTab(TABS.MEMBERS_TAB);
  };
  var handleSelectMember = function handleSelectMember(member) {
    setSelectedMember(member);
  };
  var filterMembers = function filterMembers(members) {
    if (filterMembersBy === null) {
      return members;
    }
    return filter(prop(filterMembersBy), members);
  };
  return /*#__PURE__*/jsxs(Fragment, {
    children: [/*#__PURE__*/jsx(TabHeader, {
      loading: loading,
      memberTitle: memberTitle,
      selectedMember: selectedMember,
      selectedTab: selectedTab,
      selectedTeam: selectedTeam,
      setSelectedTab: setSelectedTab,
      showTeams: showTeams,
      teamTitle: teamTitle,
      onClearMember: function onClearMember() {
        return setSelectedMember({
          id: null
        });
      },
      onClearTeam: function onClearTeam() {
        return setSelectedTeam({
          id: null
        });
      }
    }), /*#__PURE__*/jsx(TabBody, {
      loading: loading,
      memberTitle: memberTitle,
      selectedMember: selectedMember,
      selectedTab: selectedTab,
      selectedTeam: selectedTeam,
      showTeams: showTeams,
      teamTitle: teamTitle,
      teams: teams,
      setMember: handleSelectMember,
      setTeam: handleSelectTeam,
      members: selectedTeam !== null && selectedTeam !== void 0 && selectedTeam.members ? filterMembers(selectedTeam.members) : members
    })]
  });
};

var Button = function Button(_ref) {
  var label = _ref.label,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    _ref$handleClick = _ref.handleClick,
    handleClick = _ref$handleClick === void 0 ? noop : _ref$handleClick;
  return /*#__PURE__*/jsx("button", {
    className: "w-full text-start",
    onClick: handleClick,
    children: /*#__PURE__*/jsxs("a", {
      className: classnames([{
        "cursor-not-allowed opacity-50": disabled
      }, "neeto-ui-btn neeto-ui-btn--style-text neeto-ui-btn--width-full neeto-ui-btn--size-medium justify-start"]),
      children: [/*#__PURE__*/jsx("span", {
        className: "neeto-ui-btn__label overflow-hidden text-ellipsis whitespace-nowrap",
        style: {
          width: label !== "--" ? "calc(100% - 24px)" : "15%"
        },
        children: label
      }), /*#__PURE__*/jsx(Down, {
        className: "neeto-ui-btn__icon",
        size: 16
      })]
    })
  });
};

var Target$1 = function Target(_ref) {
  var isOpen = _ref.isOpen,
    setIsOpen = _ref.setIsOpen,
    selectedTeam = _ref.selectedTeam,
    selectedMember = _ref.selectedMember,
    canManageTicket = _ref.canManageTicket,
    module = _ref.module;
  var isChatModule = module === "chats";
  var clippedString = function clippedString(string) {
    var cap = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    return string && cap && string.length > cap ? "".concat(string.substring(0, cap), "...") : string;
  };
  var renderContent = function renderContent() {
    var charLimit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
    if (selectedTeam !== null && selectedTeam !== void 0 && selectedTeam.label && selectedMember !== null && selectedMember !== void 0 && selectedMember.label) {
      return "".concat(clippedString(selectedTeam.label, charLimit), "/").concat(clippedString(selectedMember.label, charLimit));
    }
    if (selectedTeam !== null && selectedTeam !== void 0 && selectedTeam.label) {
      return "".concat(clippedString(selectedTeam.label, charLimit), "/--");
    }
    return (selectedMember === null || selectedMember === void 0 ? void 0 : selectedMember.label) || "--";
  };
  return /*#__PURE__*/jsx(Tooltip, {
    content: renderContent(),
    children: /*#__PURE__*/jsx("span", {
      children: canManageTicket || isChatModule ? /*#__PURE__*/jsx(Button, {
        handleClick: function handleClick() {
          return setIsOpen(!isOpen);
        },
        label: renderContent(isChatModule ? 20 : 8)
      }) : /*#__PURE__*/jsx(Button, {
        disabled: true,
        label: renderContent(isChatModule ? 20 : 8)
      })
    })
  });
};
var Target = /*#__PURE__*/memo(Target$1);

var TeamsAndMembersDropdown = function TeamsAndMembersDropdown(_ref) {
  var config = _ref.config;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isOpen = _useState2[0],
    setIsOpen = _useState2[1];
  var dropdownRef = useRef(null);
  useOnClickOutside(dropdownRef, function (event) {
    var _event$target$closest, _event$target;
    if ((_event$target$closest = (_event$target = event.target).closest) !== null && _event$target$closest !== void 0 && _event$target$closest.call(_event$target, ".neeto-ui-dropdown__popup")) return;
    setIsOpen(false);
  });
  useEffect(function () {
    if (config !== null && config !== void 0 && config.loading.member) return;
    setIsOpen(false);
  }, [config === null || config === void 0 ? void 0 : config.loading.member]);
  return /*#__PURE__*/jsx("div", {
    className: "inline",
    ref: dropdownRef,
    children: /*#__PURE__*/jsx("div", {
      className: "max-w-40",
      children: /*#__PURE__*/jsx(Dropdown, {
        isOpen: isOpen,
        appendTo: function appendTo() {
          return document.body;
        },
        closeOnSelect: false,
        strategy: "fixed",
        customTarget: function customTarget() {
          return /*#__PURE__*/jsx(Target, {
            isOpen: isOpen,
            setIsOpen: setIsOpen,
            canManageTicket: config === null || config === void 0 ? void 0 : config.canManageTicket,
            module: config === null || config === void 0 ? void 0 : config.module,
            selectedMember: config === null || config === void 0 ? void 0 : config.selectedMember,
            selectedTeam: config === null || config === void 0 ? void 0 : config.selectedTeam
          });
        },
        onClose: function onClose() {
          return setIsOpen(false);
        },
        children: /*#__PURE__*/jsx(DropDownContent, {
          filterMembersBy: config === null || config === void 0 ? void 0 : config.filterMembersBy,
          loading: config === null || config === void 0 ? void 0 : config.loading,
          memberTitle: config === null || config === void 0 ? void 0 : config.memberTitle,
          selectedMember: config === null || config === void 0 ? void 0 : config.selectedMember,
          selectedTeam: config === null || config === void 0 ? void 0 : config.selectedTeam,
          setSelectedMember: config === null || config === void 0 ? void 0 : config.setSelectedMember,
          setSelectedTeam: config === null || config === void 0 ? void 0 : config.setSelectedTeam,
          teamTitle: config === null || config === void 0 ? void 0 : config.teamTitle,
          teams: config === null || config === void 0 ? void 0 : config.teams,
          members: config !== null && config !== void 0 && config.filterMembersBy ? filter(prop(config === null || config === void 0 ? void 0 : config.filterMembersBy), config === null || config === void 0 ? void 0 : config.members) : config === null || config === void 0 ? void 0 : config.members
        })
      })
    })
  });
};

export { TeamsAndMembersDropdown as default };
//# sourceMappingURL=TeamsAndMembersDropdown.js.map
