"use strict";

exports.__esModule = true;
exports.default = _default;

var _react = _interopRequireWildcard(require("react"));

var _reactIntl = require("react-intl");

var _Autocomplete = _interopRequireDefault(require("@mui/material/Autocomplete"));

var _TextField = _interopRequireDefault(require("@mui/material/TextField"));

var _CircularProgress = _interopRequireDefault(require("@mui/material/CircularProgress"));

var _Checkbox = _interopRequireDefault(require("@mui/material/Checkbox"));

var _parse = _interopRequireDefault(require("autosuggest-highlight/parse"));

var _match = _interopRequireDefault(require("autosuggest-highlight/match"));

var _material = require("@mui/material");

var _core = require("@selfcommunity/core");

var _styles = require("@mui/material/styles");

var _useThemeProps = _interopRequireDefault(require("@mui/material/styles/useThemeProps"));

const _excluded = ["onChange", "defaultValue", "limitCountCategories", "checkboxSelect", "disabled", "TextFieldProps"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

const PREFIX = 'SCComposerCategories';
const classes = {
  root: `${PREFIX}-root`
};
const Root = (0, _styles.styled)(_Autocomplete.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(() => ({
  minWidth: 120
}));

function _default(inProps) {
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  }); // Props

  const {
    onChange,
    defaultValue = [],
    limitCountCategories = 0,
    checkboxSelect = false,
    disabled = false,
    TextFieldProps = {
      variant: 'outlined',
      label: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.composer.categories.label",
        defaultMessage: "ui.composer.categories.label"
      })
    }
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // State


  const [open, setOpen] = (0, _react.useState)(false);
  const [value, setValue] = (0, _react.useState)(defaultValue); // HOOKS

  const {
    categories,
    isLoading
  } = (0, _core.useSCFetchCategories)();
  (0, _react.useEffect)(() => {
    onChange && onChange(value);
  }, [value]); // Handlers

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const handleChange = (event, value) => {
    let newValue = null;

    if (limitCountCategories > 0) {
      const [...rest] = value;
      newValue = rest.slice(-1 * limitCountCategories);
    } else {
      newValue = value;
    }

    setValue(newValue);
  }; // Render


  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    className: classes.root,
    open: open,
    onOpen: handleOpen,
    onClose: handleClose,
    filterSelectedOptions: !checkboxSelect,
    disableCloseOnSelect: checkboxSelect,
    multiple: true,
    options: categories || [],
    getOptionLabel: option => option.name || '',
    value: value,
    selectOnFocus: true,
    clearOnBlur: true,
    blurOnSelect: true,
    handleHomeEndKeys: true,
    clearIcon: null,
    disabled: disabled,
    noOptionsText: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.categories.empty",
      defaultMessage: "ui.composer.categories.empty"
    }),
    onChange: handleChange,
    isOptionEqualToValue: (option, value) => value.id === option.id,
    renderTags: (value, getTagProps) => {
      return value.map((option, index) => /*#__PURE__*/_react.default.createElement(_material.Chip, _extends({
        key: option.id,
        id: option.id,
        label: option.name,
        color: option.color
      }, getTagProps({
        index
      }))));
    },
    renderOption: (props, option, {
      selected,
      inputValue
    }) => {
      const matches = (0, _match.default)(option.name, inputValue);
      const parts = (0, _parse.default)(option.name, matches);
      return /*#__PURE__*/_react.default.createElement("li", props, checkboxSelect && /*#__PURE__*/_react.default.createElement(_Checkbox.default, {
        style: {
          marginRight: 8
        },
        checked: selected
      }), /*#__PURE__*/_react.default.createElement(_material.Chip, {
        label: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, parts.map((part, index) => /*#__PURE__*/_react.default.createElement("span", {
          key: index,
          style: {
            fontWeight: part.highlight ? 700 : 400
          }
        }, part.text)))
      }));
    },
    renderInput: params => {
      return /*#__PURE__*/_react.default.createElement(_TextField.default, _extends({}, params, TextFieldProps, {
        margin: "dense",
        InputProps: Object.assign({}, params.InputProps, {
          autoComplete: 'categories',
          // disable autocomplete and autofill
          endAdornment: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, isLoading ? /*#__PURE__*/_react.default.createElement(_CircularProgress.default, {
            color: "inherit",
            size: 20
          }) : null, params.InputProps.endAdornment)
        })
      }));
    }
  }, rest));
}