"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = tslib_1.__importStar(require("react"));
const react_intl_1 = require("react-intl");
const Autocomplete_1 = tslib_1.__importDefault(require("@mui/material/Autocomplete"));
const TextField_1 = tslib_1.__importDefault(require("@mui/material/TextField"));
const CircularProgress_1 = tslib_1.__importDefault(require("@mui/material/CircularProgress"));
const Checkbox_1 = tslib_1.__importDefault(require("@mui/material/Checkbox"));
const parse_1 = tslib_1.__importDefault(require("autosuggest-highlight/parse"));
const match_1 = tslib_1.__importDefault(require("autosuggest-highlight/match"));
const material_1 = require("@mui/material");
const react_core_1 = require("@selfcommunity/react-core");
const styles_1 = require("@mui/material/styles");
const system_1 = require("@mui/system");
const PREFIX = 'SCCategoryAutocomplete';
const classes = {
    root: `${PREFIX}-root`
};
const Root = (0, styles_1.styled)(Autocomplete_1.default, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(() => ({}));
/**
 * > API documentation for the Community-JS Category Autocomplete component. Learn about the available props and the CSS API.
 *
 *
 * This component renders a bar that allows users to search (with autocomplete) for all the categories available in the application.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/CategoryAutocomplete)
 *
 * #### Import
 *  ```jsx
 *  import {CategoryAutocomplete} from '@selfcommunity/react-ui';
 *  ```
 *  #### Component Name
 *  The name `SCCategoryAutocomplete` can be used when providing style overrides in the theme.
 *
 *  #### CSS
 *
 *  |Rule Name|Global class|Description|
 *  |---|---|---|
 *  |root|.SCCategoryAutocomplete-root|Styles applied to the root element.|
 *
 * @param inProps
 */
const CategoryAutocomplete = (inProps) => {
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    // Props
    const { onChange, multiple = false, defaultValue = multiple ? [] : null, limitCountCategories = 0, checkboxSelect = false, disabled = false, TextFieldProps = {
        variant: 'outlined',
        label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.categoryAutocomplete.label", defaultMessage: "ui.categoryAutocomplete.label" })
    } } = props, rest = tslib_1.__rest(props, ["onChange", "multiple", "defaultValue", "limitCountCategories", "checkboxSelect", "disabled", "TextFieldProps"]);
    // State
    const [open, setOpen] = (0, react_1.useState)(false);
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore
    const [value, setValue] = (0, react_1.useState)(typeof defaultValue === 'string' ? null : defaultValue);
    // HOOKS
    const { categories, isLoading } = (0, react_core_1.useSCFetchCategories)();
    (0, react_1.useEffect)(() => {
        if (value === null) {
            return;
        }
        onChange && onChange(value);
    }, [value]);
    (0, react_1.useEffect)(() => {
        if (!isLoading && typeof defaultValue === 'string') {
            setValue(multiple ? categories.filter((cat) => cat.id === Number(defaultValue)) : categories.find((cat) => cat.id === Number(defaultValue)));
        }
    }, [isLoading]);
    // Handlers
    const handleOpen = () => {
        setOpen(true);
    };
    const handleClose = () => {
        setOpen(false);
    };
    const handleChange = (event, value) => {
        let newValue = null;
        if (multiple && limitCountCategories > 0) {
            const [...rest] = value;
            newValue = rest.slice(-1 * limitCountCategories);
        }
        else {
            newValue = value;
        }
        setValue(newValue);
    };
    // Render
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ className: classes.root, multiple: multiple, open: open, onOpen: handleOpen, onClose: handleClose, filterSelectedOptions: !checkboxSelect, disableCloseOnSelect: checkboxSelect, options: categories || [], getOptionLabel: (option) => option.name || '', value: value, selectOnFocus: true, clearOnBlur: true, blurOnSelect: true, handleHomeEndKeys: true, clearIcon: null, disabled: disabled || isLoading, noOptionsText: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.categoryAutocomplete.empty", defaultMessage: "ui.categoryAutocomplete.empty" }), onChange: handleChange, isOptionEqualToValue: (option, value) => value.id === option.id, renderTags: (value, getTagProps) => {
            return value.map((option, index) => ((0, jsx_runtime_1.jsx)(material_1.Chip, Object.assign({ id: option.id, label: option.name, color: option.color }, getTagProps({ index })), option.id)));
        }, renderOption: (props, option, { selected, inputValue }) => {
            const matches = (0, match_1.default)(option.name, inputValue);
            const parts = (0, parse_1.default)(option.name, matches);
            return ((0, jsx_runtime_1.jsxs)("li", Object.assign({}, props, { children: [checkboxSelect && (0, jsx_runtime_1.jsx)(Checkbox_1.default, { style: { marginRight: 8 }, checked: selected }), (0, jsx_runtime_1.jsx)(material_1.Chip, { label: (0, jsx_runtime_1.jsx)(react_1.default.Fragment, { children: parts.map((part, index) => ((0, jsx_runtime_1.jsx)("span", Object.assign({ style: { fontWeight: part.highlight ? 700 : 400 } }, { children: part.text }), index))) }) })] })));
        }, renderInput: (params) => {
            return ((0, jsx_runtime_1.jsx)(TextField_1.default, Object.assign({}, params, TextFieldProps, { margin: "dense", InputProps: Object.assign(Object.assign({}, params.InputProps), { autoComplete: 'categories', endAdornment: ((0, jsx_runtime_1.jsxs)(react_1.default.Fragment, { children: [isLoading ? (0, jsx_runtime_1.jsx)(CircularProgress_1.default, { color: "inherit", size: 20 }) : null, params.InputProps.endAdornment] })) }) })));
        } }, rest)));
};
exports.default = CategoryAutocomplete;
