'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');
var i18next = require('i18next');
var neetoCist = require('@bigbinary/neeto-cist');
var initializers = require('@bigbinary/neeto-commons-frontend/initializers');
var Alert = require('@bigbinary/neetoui/Alert');
var NoData = require('@bigbinary/neetoui/NoData');
var Table = require('@bigbinary/neetoui/Table');
var Toastr = require('@bigbinary/neetoui/Toastr');
var ramda = require('ramda');
var reactI18next = require('react-i18next');
var Container = require('./Container.js');
var Header = require('./Header.js');
var SubHeader = require('./SubHeader.js');
var TableWrapper = require('./TableWrapper.js');
var constants = require('@bigbinary/neeto-commons-frontend/constants');
var utils = require('@bigbinary/neeto-commons-frontend/utils');
var Pane = require('@bigbinary/neetoui/Pane');
var Typography = require('@bigbinary/neetoui/Typography');
var ActionBlock = require('@bigbinary/neetoui/formik/ActionBlock');
var Form = require('@bigbinary/neetoui/formik/Form');
var Input = require('@bigbinary/neetoui/formik/Input');
var yup = require('yup');
var reactQuery = require('@tanstack/react-query');
var axios = require('axios');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var MoreDropdown = require('./MoreDropdown.js');
var jsxRuntime = require('react/jsx-runtime');
var Dropdown = require('@bigbinary/neetoui/Dropdown');
require('classnames');
require('./index-JY2zVpnv.js');
require('./_commonjsHelpers-BJu3ubxk.js');
require('./inject-css-B6qYtOJe.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('./Breadcrumbs.js');
require('@bigbinary/neeto-commons-frontend/utils/general');
require('react-router-dom');
require('./HelpPopover.js');
require('@bigbinary/neeto-icons/Help');
require('@bigbinary/neetoui/Button');
require('@bigbinary/neetoui/Popover');
require('./Search.js');
require('@bigbinary/neeto-commons-frontend/react-utils/useFuncDebounce');
require('@bigbinary/neeto-commons-frontend/react-utils/useQueryParams');
require('@bigbinary/neeto-commons-frontend/react-utils/useUpdateEffect');
require('@bigbinary/neeto-icons/Search');
require('@bigbinary/neetoui/Input');
require('@bigbinary/neeto-icons/MenuHorizontal');
require('@bigbinary/neeto-icons/MenuVertical');
require('@bigbinary/neetoui/Tooltip');
require('@bigbinary/neeto-commons-frontend/react-utils');
require('@bigbinary/neeto-icons/Column');
require('./Columns-DHPNrFgq.js');
require('@dnd-kit/core');
require('@dnd-kit/sortable');
require('@bigbinary/neetoui/Checkbox');
require('@bigbinary/neetoui/Label');
require('@bigbinary/neeto-icons/Reorder');
require('@bigbinary/neeto-commons-frontend/react-utils/useMutationWithInvalidation');
require('@bigbinary/neeto-icons/Download');
require('@bigbinary/neeto-filters-frontend/Filters');
require('@bigbinary/neeto-icons/Filter');

function _interopNamespaceDefault(e) {
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var yup__namespace = /*#__PURE__*/_interopNamespaceDefault(yup);

var LABEL_REJECT_CHARS_REGEX = /[^a-zA-Z\d\s_-]+/;
var VALIDATION_SCHEMA = yup__namespace.object().shape({
  singularLabel: yup__namespace.string().trim().required(i18next.t("neetoMolecules.taxonomy.editPane.validations.singularLabelRequired")),
  pluralLabel: yup__namespace.string().trim().required(i18next.t("neetoMolecules.taxonomy.editPane.validations.pluralLabelRequired"))
});
var TAXONOMY_EVENTS = {
  UPDATED: "taxonomy_updated"
};

var update = function update(_ref) {
  var keyName = _ref.keyName,
    payload = _ref.payload;
  return axios.patch("".concat(constants.BASE_API_V1_URL, "/taxonomies/").concat(keyName), payload);
};
var bulkDestroy = function bulkDestroy(payload) {
  return axios["delete"]("".concat(constants.BASE_API_V1_URL, "/taxonomies/bulk_destroy"), {
    data: payload
  });
};
var taxonomiesApi = {
  update: update,
  bulkDestroy: bulkDestroy
};

function ownKeys$2(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$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var useUpdateTaxonomy = function useUpdateTaxonomy(options) {
  return reactQuery.useMutation(_objectSpread$2({
    mutationFn: taxonomiesApi.update
  }, options));
};
var useBulkDestroyTaxonomies = function useBulkDestroyTaxonomies(options) {
  return reactQuery.useMutation(_objectSpread$2({
    mutationFn: taxonomiesApi.bulkDestroy
  }, options));
};

var formatLabel = function formatLabel(label) {
  return neetoCist.capitalize(label.trim());
};
var formatDataForTable = function formatDataForTable(taxonomies) {
  return ramda.toPairs(taxonomies).map(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 2),
      keyName = _ref2[0],
      labels = _ref2[1];
    return {
      keyName: keyName,
      singularLabel: labels["singular"],
      pluralLabel: labels["plural"]
    };
  });
};
var getColumnData = function getColumnData(_ref3) {
  var columnLabels = _ref3.columnLabels,
    columnsToShow = _ref3.columnsToShow,
    handleEdit = _ref3.handleEdit,
    setCurrentKeys = _ref3.setCurrentKeys,
    setIsResetModalOpen = _ref3.setIsResetModalOpen;
  var _columnsToShow$singul = columnsToShow.singularColumn,
    showSingularColumn = _columnsToShow$singul === void 0 ? true : _columnsToShow$singul,
    _columnsToShow$plural = columnsToShow.pluralColumn,
    showPluralColumn = _columnsToShow$plural === void 0 ? true : _columnsToShow$plural;
  var _columnLabels$singula = columnLabels.singular,
    singularLabel = _columnLabels$singula === void 0 ? i18next.t("neetoMolecules.taxonomy.singularLabel") : _columnLabels$singula,
    _columnLabels$plural = columnLabels.plural,
    pluralLabel = _columnLabels$plural === void 0 ? i18next.t("neetoMolecules.taxonomy.pluralLabel") : _columnLabels$plural;
  return [{
    title: i18next.t("neetoMolecules.taxonomy.defaultLabel"),
    dataIndex: "default",
    key: "defaultLabel",
    width: 400,
    render: function render(_, values) {
      var menuItems = [{
        key: "edit",
        label: i18next.t("neetoMolecules.common.actions.edit"),
        onClick: function onClick() {
          return handleEdit(values);
        }
      }, {
        key: "reset",
        label: i18next.t("neetoMolecules.common.actions.resetToDefaults"),
        onClick: function onClick() {
          setCurrentKeys([values.keyName]);
          setIsResetModalOpen(true);
        }
      }];
      return /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "flex items-center justify-between gap-x-3",
        children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
          style: "body2",
          children: i18next.t("taxonomyDefaultLabels.".concat(values.keyName, ".singular"))
        }), /*#__PURE__*/jsxRuntime.jsx(MoreDropdown, {
          menuItems: menuItems,
          dropdownButtonProps: {
            "data-testid": "nui-dropdown-icon-".concat(values.keyName),
            className: "me-1 my-1"
          },
          dropdownProps: {
            strategy: "fixed",
            placement: "bottom-end",
            appendTo: function appendTo() {
              return document.body;
            }
          }
        })]
      });
    }
  }].concat(_toConsumableArray(showSingularColumn ? [{
    title: singularLabel,
    dataIndex: "singularLabel",
    key: "singularLabel",
    width: 300
  }] : []), _toConsumableArray(showPluralColumn ? [{
    title: pluralLabel,
    dataIndex: "pluralLabel",
    key: "pluralLabel",
    width: 300
  }] : []));
};
var getFilteredTaxonomies = function getFilteredTaxonomies(matchString, taxonomies) {
  var filteredArray = ramda.toPairs(taxonomies).filter(function (_ref4) {
    var _ref5 = _slicedToArray(_ref4, 2),
      key = _ref5[0],
      value = _ref5[1];
    var defaultLabel = i18next.t("taxonomyDefaultLabels.".concat(key, ".singular"));
    var valuesToSearch = [defaultLabel].concat(_toConsumableArray(Object.values(value)));
    return valuesToSearch.some(function (str) {
      return str.toLowerCase().includes(matchString.toLowerCase());
    });
  });
  return ramda.fromPairs(filteredArray);
};

function ownKeys$1(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$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var EditPane = function EditPane(_ref) {
  var columnLabels = _ref.columnLabels,
    columnsToShow = _ref.columnsToShow,
    initialValues = _ref.initialValues,
    isOpen = _ref.isOpen,
    onClose = _ref.onClose;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var initialFocusRef = React.useRef(null);
  var _useUpdateTaxonomy = useUpdateTaxonomy(),
    updateTaxonomy = _useUpdateTaxonomy.mutate;
  var _columnsToShow$singul = columnsToShow.singularColumn,
    showSingularInputField = _columnsToShow$singul === void 0 ? true : _columnsToShow$singul,
    _columnsToShow$plural = columnsToShow.pluralColumn,
    showPluralInputField = _columnsToShow$plural === void 0 ? true : _columnsToShow$plural;
  var _columnLabels$singula = columnLabels.singular,
    singularLabel = _columnLabels$singula === void 0 ? t("neetoMolecules.taxonomy.singularLabel") : _columnLabels$singula,
    _columnLabels$plural = columnLabels.plural,
    pluralLabel = _columnLabels$plural === void 0 ? t("neetoMolecules.taxonomy.pluralLabel") : _columnLabels$plural;
  var handleSubmit = function handleSubmit(values, _ref2) {
    var setSubmitting = _ref2.setSubmitting;
    var keyName = values.keyName,
      singularLabel = values.singularLabel,
      pluralLabel = values.pluralLabel;
    var payload = {
      taxonomy: {
        keyName: keyName,
        singularLabel: formatLabel(singularLabel),
        pluralLabel: formatLabel(pluralLabel)
      }
    };
    var options = {
      onSuccess: function onSuccess() {
        utils.captureAnalyticsEvent(TAXONOMY_EVENTS.UPDATED, {
          taxonomy: payload.taxonomy
        });
        window.location.reload();
      },
      onError: function onError(error) {
        return Toastr.error(error);
      },
      onSettled: function onSettled() {
        return setSubmitting(false);
      }
    };
    updateTaxonomy({
      keyName: keyName,
      payload: payload
    }, options);
  };
  return /*#__PURE__*/jsxRuntime.jsxs(Pane, {
    initialFocusRef: initialFocusRef,
    isOpen: isOpen,
    onClose: onClose,
    "data-testid": "taxonomy-edit-pane",
    children: [/*#__PURE__*/jsxRuntime.jsx(Pane.Header, {
      children: /*#__PURE__*/jsxRuntime.jsx(Typography, {
        style: "h2",
        weight: "semibold",
        children: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
          i18nKey: "neetoMolecules.taxonomy.editPane.title",
          values: _objectSpread$1({
            entity: t("taxonomyDefaultLabels.".concat(initialValues.keyName, ".singular"))
          }, showSingularInputField && showPluralInputField ? constants.PLURAL : constants.SINGULAR)
        })
      })
    }), /*#__PURE__*/jsxRuntime.jsxs(Form, {
      formikProps: {
        initialValues: initialValues,
        validationSchema: VALIDATION_SCHEMA,
        onSubmit: handleSubmit
      },
      children: [/*#__PURE__*/jsxRuntime.jsx(Pane.Body, {
        children: /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "flex w-full flex-col gap-y-6",
          children: [showSingularInputField && /*#__PURE__*/jsxRuntime.jsx(Input, {
            required: true,
            className: "w-full",
            "data-cy": "taxonomy-singular-input-field",
            "data-testid": "taxonomy-singular-input-field",
            label: singularLabel,
            name: "singularLabel",
            ref: initialFocusRef,
            rejectCharsRegex: LABEL_REJECT_CHARS_REGEX
          }), showPluralInputField && /*#__PURE__*/jsxRuntime.jsx(Input, {
            required: true,
            className: "w-full",
            "data-cy": "taxonomy-plural-input-field",
            "data-testid": "taxonomy-plural-input-field",
            label: pluralLabel,
            name: "pluralLabel",
            rejectCharsRegex: LABEL_REJECT_CHARS_REGEX
          })]
        })
      }), /*#__PURE__*/jsxRuntime.jsx(Pane.Footer, {
        children: /*#__PURE__*/jsxRuntime.jsx(ActionBlock, {
          cancelButtonProps: {
            onClick: onClose,
            disabled: false
          },
          className: "flex items-center gap-x-2"
        })
      })]
    })]
  });
};

var LeftActionBlock = function LeftActionBlock(_ref) {
  var selectedCount = _ref.selectedCount,
    totalCount = _ref.totalCount,
    setIsResetModalOpen = _ref.setIsResetModalOpen,
    setCurrentKeys = _ref.setCurrentKeys,
    selectedRowIds = _ref.selectedRowIds;
  var Menu = Dropdown.Menu,
    MenuItem = Dropdown.MenuItem;
  return !!totalCount && /*#__PURE__*/jsxRuntime.jsx(jsxRuntime.Fragment, {
    children: selectedCount > 0 ? /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
      children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
        className: "me-4 font-semibold",
        component: "h4",
        "data-cy": "item-count",
        children: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
          i18nKey: "neetoMolecules.taxonomy.actionBlock.selectedTaxonomy",
          values: {
            count: selectedCount,
            totalCount: totalCount
          },
          components: {
            span: /*#__PURE__*/jsxRuntime.jsx("span", {
              className: "neeto-ui-text-gray-600"
            })
          }
        })
      }), /*#__PURE__*/jsxRuntime.jsx(Dropdown, {
        buttonStyle: "secondary",
        label: i18next.t("neetoMolecules.taxonomy.actionBlock.takeAction"),
        children: /*#__PURE__*/jsxRuntime.jsx(Menu, {
          children: /*#__PURE__*/jsxRuntime.jsx(MenuItem.Button, {
            style: "secondary",
            onClick: function onClick() {
              setCurrentKeys(selectedRowIds);
              setIsResetModalOpen(true);
            },
            children: i18next.t("neetoMolecules.common.actions.resetToDefaults")
          })
        })
      })]
    }) : /*#__PURE__*/jsxRuntime.jsx(Typography, {
      className: "me-4 font-semibold",
      component: "h4",
      "data-cy": "item-count",
      children: i18next.t("neetoMolecules.taxonomy.actionBlock.taxonomyWithCount", {
        count: totalCount
      })
    })
  });
};

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 Taxonomy = function Taxonomy(_ref) {
  var breadcrumbs = _ref.breadcrumbs,
    _ref$columnLabels = _ref.columnLabels,
    columnLabels = _ref$columnLabels === void 0 ? {} : _ref$columnLabels,
    _ref$columnsToShow = _ref.columnsToShow,
    columnsToShow = _ref$columnsToShow === void 0 ? {} : _ref$columnsToShow,
    _ref$titleHelpPopover = _ref.titleHelpPopoverProps,
    titleHelpPopoverProps = _ref$titleHelpPopover === void 0 ? {} : _ref$titleHelpPopover;
  var _useState = React.useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isResetModalOpen = _useState2[0],
    setIsResetModalOpen = _useState2[1];
  var _useState3 = React.useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isEditTaxonomyPaneOpen = _useState4[0],
    setIsEditTaxonomyPaneOpen = _useState4[1];
  var _useState5 = React.useState({}),
    _useState6 = _slicedToArray(_useState5, 2),
    initialValues = _useState6[0],
    setInitialValues = _useState6[1];
  var _useState7 = React.useState([]),
    _useState8 = _slicedToArray(_useState7, 2),
    selectedRowIds = _useState8[0],
    setSelectedRowIds = _useState8[1];
  var _useState9 = React.useState(""),
    _useState0 = _slicedToArray(_useState9, 2),
    searchString = _useState0[0],
    setSearchString = _useState0[1];
  var _useState1 = React.useState([]),
    _useState10 = _slicedToArray(_useState1, 2),
    currentKeys = _useState10[0],
    setCurrentKeys = _useState10[1];
  var _useBulkDestroyTaxono = useBulkDestroyTaxonomies(),
    bulkDestroyTaxonomies = _useBulkDestroyTaxono.mutate;
  var hostTaxonomyKeys = ramda.keys(initializers.globalProps.taxonomies);
  var hostTaxonomies = ramda.pick(hostTaxonomyKeys, initializers.taxonomies);
  var _useState11 = React.useState(hostTaxonomies),
    _useState12 = _slicedToArray(_useState11, 2),
    filteredTaxonomies = _useState12[0],
    setFilteredTaxonomies = _useState12[1];
  var handleRowSelect = function handleRowSelect(ids) {
    return setSelectedRowIds(ids);
  };
  var handleDelete = function handleDelete() {
    var payload = {
      keyNames: currentKeys
    };
    var options = {
      onSuccess: function onSuccess() {
        return window.location.reload();
      },
      onError: function onError(error) {
        return Toastr.error(error);
      }
    };
    bulkDestroyTaxonomies(payload, options);
  };
  var handleEdit = function handleEdit(values) {
    setInitialValues(values);
    setIsEditTaxonomyPaneOpen(true);
  };
  var handleSearch = function handleSearch(event) {
    setSearchString(event.target.value);
    var newTaxonomies = getFilteredTaxonomies(event.target.value, hostTaxonomies);
    setFilteredTaxonomies(newTaxonomies);
  };
  return /*#__PURE__*/jsxRuntime.jsxs(Container, {
    children: [/*#__PURE__*/jsxRuntime.jsx(Header, {
      breadcrumbs: breadcrumbs,
      title: i18next.t("neetoMolecules.taxonomy.title"),
      searchProps: {
        onChange: handleSearch,
        value: searchString,
        placeholder: i18next.t("neetoMolecules.taxonomy.searchTaxonomy")
      },
      titleHelpPopoverProps: _objectSpread({
        description: i18next.t("neetoMolecules.taxonomy.description"),
        title: i18next.t("neetoMolecules.taxonomy.title")
      }, titleHelpPopoverProps)
    }), /*#__PURE__*/jsxRuntime.jsx(SubHeader, {
      leftActionBlock: /*#__PURE__*/jsxRuntime.jsx(LeftActionBlock, {
        selectedRowIds: selectedRowIds,
        setCurrentKeys: setCurrentKeys,
        setIsResetModalOpen: setIsResetModalOpen,
        selectedCount: selectedRowIds.length,
        totalCount: Object.entries(filteredTaxonomies).length
      })
    }), neetoCist.isNotEmpty(filteredTaxonomies) ? /*#__PURE__*/jsxRuntime.jsxs(TableWrapper, {
      children: [/*#__PURE__*/jsxRuntime.jsx(Table, {
        fixedHeight: true,
        rowSelection: true,
        allowRowClick: false,
        rowData: formatDataForTable(filteredTaxonomies),
        rowKey: ramda.prop("keyName"),
        selectedRowKeys: selectedRowIds,
        tableLayout: "fixed",
        columnData: getColumnData({
          columnLabels: columnLabels,
          columnsToShow: columnsToShow,
          handleEdit: handleEdit,
          setCurrentKeys: setCurrentKeys,
          setIsResetModalOpen: setIsResetModalOpen
        }),
        onRowSelect: handleRowSelect
      }), /*#__PURE__*/jsxRuntime.jsx(EditPane, {
        columnLabels: columnLabels,
        columnsToShow: columnsToShow,
        initialValues: initialValues,
        isOpen: isEditTaxonomyPaneOpen,
        onClose: function onClose() {
          return setIsEditTaxonomyPaneOpen(false);
        }
      }), /*#__PURE__*/jsxRuntime.jsx(Alert, {
        isOpen: isResetModalOpen,
        submitButtonLabel: i18next.t("neetoMolecules.common.actions.proceed"),
        title: i18next.t("neetoMolecules.taxonomy.resetAlert.title"),
        message: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
          i18nKey: "neetoMolecules.taxonomy.resetAlert.message",
          values: {
            count: currentKeys.length,
            what: i18next.t("taxonomyDefaultLabels.".concat(currentKeys[0], ".singular"))
          }
        }),
        onClose: function onClose() {
          return setIsResetModalOpen(false);
        },
        onSubmit: handleDelete
      })]
    }) : /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "flex h-full w-full items-center justify-center",
      children: /*#__PURE__*/jsxRuntime.jsx(NoData, {
        title: i18next.t("neetoMolecules.taxonomy.noData")
      })
    })]
  });
};

module.exports = Taxonomy;
//# sourceMappingURL=Taxonomy.js.map
