import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { useRef, useState } from 'react';
import { t } from 'i18next';
import { capitalize, isNotEmpty } from '@bigbinary/neeto-cist';
import { globalProps, taxonomies } from '@bigbinary/neeto-commons-frontend/initializers';
import Alert from '@bigbinary/neetoui/Alert';
import NoData from '@bigbinary/neetoui/NoData';
import Table from '@bigbinary/neetoui/Table';
import Toastr from '@bigbinary/neetoui/Toastr';
import { toPairs, fromPairs, keys, pick, prop } from 'ramda';
import { useTranslation, Trans } from 'react-i18next';
import Container from './Container.js';
import Header from './Header.js';
import SubHeader from './SubHeader.js';
import TableWrapper from './TableWrapper.js';
import { BASE_API_V1_URL, PLURAL, SINGULAR } from '@bigbinary/neeto-commons-frontend/constants';
import { captureAnalyticsEvent } from '@bigbinary/neeto-commons-frontend/utils';
import Pane from '@bigbinary/neetoui/Pane';
import Typography from '@bigbinary/neetoui/Typography';
import ActionBlock from '@bigbinary/neetoui/formik/ActionBlock';
import Form from '@bigbinary/neetoui/formik/Form';
import Input from '@bigbinary/neetoui/formik/Input';
import * as yup from 'yup';
import { useMutation } from '@tanstack/react-query';
import axios from 'axios';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import MoreDropdown from './MoreDropdown.js';
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import Dropdown from '@bigbinary/neetoui/Dropdown';
import 'classnames';
import './index-DAYCJu79.js';
import './_commonjsHelpers-BFTU3MAI.js';
import './inject-css-C2dztUxs.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import './Breadcrumbs.js';
import '@bigbinary/neeto-commons-frontend/utils/general';
import 'react-router-dom';
import './HelpPopover.js';
import '@bigbinary/neeto-icons/Help';
import '@bigbinary/neetoui/Button';
import '@bigbinary/neetoui/Popover';
import './Search.js';
import '@bigbinary/neeto-commons-frontend/react-utils/useFuncDebounce';
import '@bigbinary/neeto-commons-frontend/react-utils/useQueryParams';
import '@bigbinary/neeto-commons-frontend/react-utils/useUpdateEffect';
import '@bigbinary/neeto-icons/Search';
import '@bigbinary/neetoui/Input';
import '@bigbinary/neeto-icons/MenuHorizontal';
import '@bigbinary/neeto-icons/MenuVertical';
import '@bigbinary/neetoui/Tooltip';
import '@bigbinary/neeto-commons-frontend/react-utils';
import '@bigbinary/neeto-icons/Column';
import './Columns-CsOYfWFt.js';
import '@dnd-kit/core';
import '@dnd-kit/sortable';
import '@bigbinary/neetoui/Checkbox';
import '@bigbinary/neetoui/Label';
import '@bigbinary/neeto-icons/Reorder';
import '@bigbinary/neeto-commons-frontend/react-utils/useMutationWithInvalidation';
import '@bigbinary/neeto-icons/Download';
import '@bigbinary/neeto-filters-frontend/Filters';
import '@bigbinary/neeto-icons/Filter';

var LABEL_REJECT_CHARS_REGEX = /[^a-zA-Z\d\s_-]+/;
var VALIDATION_SCHEMA = yup.object().shape({
  singularLabel: yup.string().trim().required(t("neetoMolecules.taxonomy.editPane.validations.singularLabelRequired")),
  pluralLabel: yup.string().trim().required(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(BASE_API_V1_URL, "/taxonomies/").concat(keyName), payload);
};
var bulkDestroy = function bulkDestroy(payload) {
  return axios["delete"]("".concat(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 useMutation(_objectSpread$2({
    mutationFn: taxonomiesApi.update
  }, options));
};
var useBulkDestroyTaxonomies = function useBulkDestroyTaxonomies(options) {
  return useMutation(_objectSpread$2({
    mutationFn: taxonomiesApi.bulkDestroy
  }, options));
};

var formatLabel = function formatLabel(label) {
  return capitalize(label.trim());
};
var formatDataForTable = function formatDataForTable(taxonomies) {
  return 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 ? t("neetoMolecules.taxonomy.singularLabel") : _columnLabels$singula,
    _columnLabels$plural = columnLabels.plural,
    pluralLabel = _columnLabels$plural === void 0 ? t("neetoMolecules.taxonomy.pluralLabel") : _columnLabels$plural;
  return [{
    title: t("neetoMolecules.taxonomy.defaultLabel"),
    dataIndex: "default",
    key: "defaultLabel",
    width: 400,
    render: function render(_, values) {
      var menuItems = [{
        key: "edit",
        label: t("neetoMolecules.common.actions.edit"),
        onClick: function onClick() {
          return handleEdit(values);
        }
      }, {
        key: "reset",
        label: t("neetoMolecules.common.actions.resetToDefaults"),
        onClick: function onClick() {
          setCurrentKeys([values.keyName]);
          setIsResetModalOpen(true);
        }
      }];
      return /*#__PURE__*/jsxs("div", {
        className: "flex items-center justify-between gap-x-3",
        children: [/*#__PURE__*/jsx(Typography, {
          style: "body2",
          children: t("taxonomyDefaultLabels.".concat(values.keyName, ".singular"))
        }), /*#__PURE__*/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 = toPairs(taxonomies).filter(function (_ref4) {
    var _ref5 = _slicedToArray(_ref4, 2),
      key = _ref5[0],
      value = _ref5[1];
    var defaultLabel = 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 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 = useTranslation(),
    t = _useTranslation.t;
  var initialFocusRef = 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() {
        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__*/jsxs(Pane, {
    initialFocusRef: initialFocusRef,
    isOpen: isOpen,
    onClose: onClose,
    "data-testid": "taxonomy-edit-pane",
    children: [/*#__PURE__*/jsx(Pane.Header, {
      children: /*#__PURE__*/jsx(Typography, {
        style: "h2",
        weight: "semibold",
        children: /*#__PURE__*/jsx(Trans, {
          i18nKey: "neetoMolecules.taxonomy.editPane.title",
          values: _objectSpread$1({
            entity: t("taxonomyDefaultLabels.".concat(initialValues.keyName, ".singular"))
          }, showSingularInputField && showPluralInputField ? PLURAL : SINGULAR)
        })
      })
    }), /*#__PURE__*/jsxs(Form, {
      formikProps: {
        initialValues: initialValues,
        validationSchema: VALIDATION_SCHEMA,
        onSubmit: handleSubmit
      },
      children: [/*#__PURE__*/jsx(Pane.Body, {
        children: /*#__PURE__*/jsxs("div", {
          className: "flex w-full flex-col gap-y-6",
          children: [showSingularInputField && /*#__PURE__*/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__*/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__*/jsx(Pane.Footer, {
        children: /*#__PURE__*/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__*/jsx(Fragment, {
    children: selectedCount > 0 ? /*#__PURE__*/jsxs(Fragment, {
      children: [/*#__PURE__*/jsx(Typography, {
        className: "me-4 font-semibold",
        component: "h4",
        "data-cy": "item-count",
        children: /*#__PURE__*/jsx(Trans, {
          i18nKey: "neetoMolecules.taxonomy.actionBlock.selectedTaxonomy",
          values: {
            count: selectedCount,
            totalCount: totalCount
          },
          components: {
            span: /*#__PURE__*/jsx("span", {
              className: "neeto-ui-text-gray-600"
            })
          }
        })
      }), /*#__PURE__*/jsx(Dropdown, {
        buttonStyle: "secondary",
        label: t("neetoMolecules.taxonomy.actionBlock.takeAction"),
        children: /*#__PURE__*/jsx(Menu, {
          children: /*#__PURE__*/jsx(MenuItem.Button, {
            style: "secondary",
            onClick: function onClick() {
              setCurrentKeys(selectedRowIds);
              setIsResetModalOpen(true);
            },
            children: t("neetoMolecules.common.actions.resetToDefaults")
          })
        })
      })]
    }) : /*#__PURE__*/jsx(Typography, {
      className: "me-4 font-semibold",
      component: "h4",
      "data-cy": "item-count",
      children: 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 = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isResetModalOpen = _useState2[0],
    setIsResetModalOpen = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isEditTaxonomyPaneOpen = _useState4[0],
    setIsEditTaxonomyPaneOpen = _useState4[1];
  var _useState5 = useState({}),
    _useState6 = _slicedToArray(_useState5, 2),
    initialValues = _useState6[0],
    setInitialValues = _useState6[1];
  var _useState7 = useState([]),
    _useState8 = _slicedToArray(_useState7, 2),
    selectedRowIds = _useState8[0],
    setSelectedRowIds = _useState8[1];
  var _useState9 = useState(""),
    _useState0 = _slicedToArray(_useState9, 2),
    searchString = _useState0[0],
    setSearchString = _useState0[1];
  var _useState1 = useState([]),
    _useState10 = _slicedToArray(_useState1, 2),
    currentKeys = _useState10[0],
    setCurrentKeys = _useState10[1];
  var _useBulkDestroyTaxono = useBulkDestroyTaxonomies(),
    bulkDestroyTaxonomies = _useBulkDestroyTaxono.mutate;
  var hostTaxonomyKeys = keys(globalProps.taxonomies);
  var hostTaxonomies = pick(hostTaxonomyKeys, taxonomies);
  var _useState11 = 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__*/jsxs(Container, {
    children: [/*#__PURE__*/jsx(Header, {
      breadcrumbs: breadcrumbs,
      title: t("neetoMolecules.taxonomy.title"),
      searchProps: {
        onChange: handleSearch,
        value: searchString,
        placeholder: t("neetoMolecules.taxonomy.searchTaxonomy")
      },
      titleHelpPopoverProps: _objectSpread({
        description: t("neetoMolecules.taxonomy.description"),
        title: t("neetoMolecules.taxonomy.title")
      }, titleHelpPopoverProps)
    }), /*#__PURE__*/jsx(SubHeader, {
      leftActionBlock: /*#__PURE__*/jsx(LeftActionBlock, {
        selectedRowIds: selectedRowIds,
        setCurrentKeys: setCurrentKeys,
        setIsResetModalOpen: setIsResetModalOpen,
        selectedCount: selectedRowIds.length,
        totalCount: Object.entries(filteredTaxonomies).length
      })
    }), isNotEmpty(filteredTaxonomies) ? /*#__PURE__*/jsxs(TableWrapper, {
      children: [/*#__PURE__*/jsx(Table, {
        fixedHeight: true,
        rowSelection: true,
        allowRowClick: false,
        rowData: formatDataForTable(filteredTaxonomies),
        rowKey: prop("keyName"),
        selectedRowKeys: selectedRowIds,
        tableLayout: "fixed",
        columnData: getColumnData({
          columnLabels: columnLabels,
          columnsToShow: columnsToShow,
          handleEdit: handleEdit,
          setCurrentKeys: setCurrentKeys,
          setIsResetModalOpen: setIsResetModalOpen
        }),
        onRowSelect: handleRowSelect
      }), /*#__PURE__*/jsx(EditPane, {
        columnLabels: columnLabels,
        columnsToShow: columnsToShow,
        initialValues: initialValues,
        isOpen: isEditTaxonomyPaneOpen,
        onClose: function onClose() {
          return setIsEditTaxonomyPaneOpen(false);
        }
      }), /*#__PURE__*/jsx(Alert, {
        isOpen: isResetModalOpen,
        submitButtonLabel: t("neetoMolecules.common.actions.proceed"),
        title: t("neetoMolecules.taxonomy.resetAlert.title"),
        message: /*#__PURE__*/jsx(Trans, {
          i18nKey: "neetoMolecules.taxonomy.resetAlert.message",
          values: {
            count: currentKeys.length,
            what: t("taxonomyDefaultLabels.".concat(currentKeys[0], ".singular"))
          }
        }),
        onClose: function onClose() {
          return setIsResetModalOpen(false);
        },
        onSubmit: handleDelete
      })]
    }) : /*#__PURE__*/jsx("div", {
      className: "flex h-full w-full items-center justify-center",
      children: /*#__PURE__*/jsx(NoData, {
        title: t("neetoMolecules.taxonomy.noData")
      })
    })]
  });
};

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