"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const material_1 = require("@mui/material");
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const react_1 = require("react");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const system_1 = require("@mui/system");
const react_intl_1 = require("react-intl");
const types_1 = require("@selfcommunity/types");
const api_services_1 = require("@selfcommunity/api-services");
const react_core_1 = require("@selfcommunity/react-core");
const messages = (0, react_intl_1.defineMessages)({
    placeholder: {
        id: 'ui.searchAutocomplete.placeholder',
        defaultMessage: 'ui.searchAutocomplete.placeholder'
    }
});
const PREFIX = 'SCSearchAutocomplete';
const classes = {
    root: `${PREFIX}-root`,
    icon: `${PREFIX}-icon`,
    input: `${PREFIX}-input`,
    clear: `${PREFIX}-clear`
};
const Root = (0, material_1.styled)(material_1.Autocomplete, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(({ theme }) => ({
    [`& .${classes.input}`]: {
        flexGrow: 1
    }
}));
function SearchAutocomplete(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    const { id = `${PREFIX}-autocomplete`, className, blurOnSelect, autoFocus = false, onSearch = null, onClear = null, onSuggestionSelect = (suggestion) => null } = props, rest = tslib_1.__rest(props, ["id", "className", "blurOnSelect", "autoFocus", "onSearch", "onClear", "onSuggestionSelect"]);
    // CONTEXT
    const scPreferences = (0, react_core_1.useSCPreferences)();
    // STATE
    const [value, setValue] = (0, react_1.useState)('');
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [options, setOptions] = (0, react_1.useState)([]);
    // INTL
    const intl = (0, react_intl_1.useIntl)();
    const handleInputChange = (event, value, reason) => {
        switch (reason) {
            case 'input':
                setValue(value);
                !value && setOptions([]);
                break;
        }
    };
    const handleChange = (event, value, reason, detail) => {
        event.preventDefault();
        event.stopPropagation();
        switch (reason) {
            case 'selectOption':
                onSuggestionSelect && onSuggestionSelect(value);
                handleClear(event);
                break;
            case 'createOption':
                onSearch && onSearch(value);
                handleClear(event);
                break;
        }
        return false;
    };
    const handleClear = (event) => {
        setValue('');
        setOptions([]);
        onClear && onClear();
    };
    const getOptionData = (option) => {
        let data = {};
        if (option.type === types_1.SuggestionType.USER) {
            data.name = option[types_1.SuggestionType.USER]['username'];
            data.image = option[types_1.SuggestionType.USER]['avatar'];
            data.variant = 'circular';
        }
        else if (option.type === types_1.SuggestionType.CATEGORY) {
            data.name = option[types_1.SuggestionType.CATEGORY]['name'];
            data.image = option[types_1.SuggestionType.CATEGORY]['image_medium'];
            data.variant = 'square';
        }
        else if (option.type === types_1.SuggestionType.GROUP) {
            data.name = option[types_1.SuggestionType.GROUP]['name'];
            data.image = option[types_1.SuggestionType.GROUP]['image_big'];
            data.variant = 'circular';
        }
        return data;
    };
    function fetchResults() {
        setIsLoading(true);
        api_services_1.SuggestionService.getSearchSuggestion(value)
            .then((data) => {
            setIsLoading(false);
            setOptions(data.results);
        })
            .catch((error) => {
            setIsLoading(false);
            console.log(error);
        });
    }
    const optionLabel = (option) => {
        switch (option.type) {
            case types_1.SuggestionType.CATEGORY:
                return option[option.type]['name_synonyms'] || option[option.type]['name'];
            case types_1.SuggestionType.USER:
                return option[option.type]['username'] && option[option.type]['real_name'];
            default:
                return option[option.type]['name'];
        }
    };
    (0, react_1.useEffect)(() => {
        if (value) {
            fetchResults();
        }
    }, [value]);
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ id: id, className: (0, classnames_1.default)(classes.root, className), blurOnSelect: blurOnSelect, onChange: handleChange, onInputChange: handleInputChange, inputValue: value, freeSolo: true, autoComplete: true, disableClearable: true, loading: isLoading, loadingText: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.searchAutocomplete.loading", defaultMessage: "ui.searchAutocomplete.loading" }), noOptionsText: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.searchAutocomplete.noOptions", defaultMessage: "ui.searchAutocomplete.noOptions" }), options: options, getOptionLabel: (option) => {
            if (typeof option === 'string') {
                return option;
            }
            return optionLabel(option);
        }, renderOption: (props, option) => ((0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ component: "li" }, props, { children: [(0, jsx_runtime_1.jsx)(material_1.Avatar, { alt: getOptionData(option).name, src: getOptionData(option).image, variant: getOptionData(option).variant }), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ ml: 1 }, { children: getOptionData(option).name }))] }))), renderInput: (params) => ((0, jsx_runtime_1.jsx)(material_1.TextField, Object.assign({}, params, { placeholder: `${intl.formatMessage(messages.placeholder, {
                community: scPreferences.preferences[react_core_1.SCPreferences.TEXT_APPLICATION_NAME].value
            })}`, InputProps: Object.assign(Object.assign({}, params.InputProps), { autoFocus, name: 'search-autocomplete', className: classes.input, startAdornment: (0, jsx_runtime_1.jsx)(Icon_1.default, Object.assign({ className: classes.icon }, { children: "search" })), endAdornment: ((0, jsx_runtime_1.jsx)(material_1.Fade, Object.assign({ in: value.length > 0 || Boolean(onClear), appear: false }, { children: (0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ className: classes.clear, onClick: handleClear, size: "small" }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "close" }) })) }))) }) }))) }, rest)));
}
exports.default = SearchAutocomplete;
