import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useEffect, useMemo, useState } from 'react';
import { FormattedMessage } from 'react-intl';
import TextField from '@mui/material/TextField';
import CircularProgress from '@mui/material/CircularProgress';
import { Autocomplete } from '@mui/material';
import { Endpoints, http } from '@selfcommunity/api-services';
import { styled } from '@mui/material/styles';
import parse from 'autosuggest-highlight/parse';
import match from 'autosuggest-highlight/match';
import { useThemeProps } from '@mui/system';
const PREFIX = 'SCLocationAutocomplete';
const classes = {
    root: `${PREFIX}-root`
};
const Root = styled(Autocomplete, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(() => ({
    minWidth: 120
}));
/**
 * > API documentation for the Community-JS Location Autocomplete component. Learn about the available props and the CSS API.
 *
 *
 * This component renders a bar that allows users to search (with autocomplete) for cities names.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/LocationAutocomplete)
 *
 * #### Import
 *  ```jsx
 *  import {LocationAutocomplete} from '@selfcommunity/react-ui';
 *  ```
 *  #### Component Name
 *  The name `SCLocationAutocomplete` can be used when providing style overrides in the theme.
 *
 *  #### CSS
 *
 *  |Rule Name|Global class|Description|
 *  |---|---|---|
 *  |root|.SCLocationAutocomplete-root|Styles applied to the root element.|
 *
 * @param inProps
 */
export default function LocationAutocomplete(inProps) {
    // Props
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { defaultValue = null, disabled = false, onChange, TextFieldProps = {
        variant: 'outlined',
        label: _jsx(FormattedMessage, { id: "ui.locationAutocomplete.label", defaultMessage: "ui.composer.locations.label" })
    } } = props, rest = __rest(props, ["defaultValue", "disabled", "onChange", "TextFieldProps"]);
    // State
    const [isLoading, setIsLoading] = useState(false);
    const [locations, setLocations] = useState([]);
    const [value, setValue] = useState(defaultValue);
    const [search, setSearch] = useState('');
    const load = (offset = 0, limit = 20) => {
        http
            .request({
            url: Endpoints.ComposerLocalitySearch.url(),
            method: Endpoints.ComposerLocalitySearch.method,
            params: {
                offset,
                limit,
                search: search.trim()
            }
        })
            .then((res) => {
            setLocations(res.data.results);
        })
            .then(() => setIsLoading(false));
    };
    // Component update
    useEffect(() => {
        if (!isLoading && search.trim().length > 0) {
            load();
        }
    }, [search]);
    useEffect(() => {
        if (value) {
            onChange && onChange(value);
        }
    }, [value]);
    // Handlers
    const handleChange = (event, value) => {
        setValue(value ? { location: value.full_address, lat: value.lat, lng: value.lng } : null);
        onChange && onChange(value);
    };
    const handleSearch = (event, _search) => {
        setSearch(_search);
    };
    // Render
    const options = useMemo(() => {
        if (!value || typeof value === 'string' || locations.find((loc) => value.lat === loc.lat && value.lng === loc.lng)) {
            return locations;
        }
        return [...locations, { lat: value.lat, lng: value.lng, full_address: value.location }];
    }, [value, locations]);
    return (_jsx(Root, Object.assign({ className: classes.root, options: options || [], 
        // @ts-ignore
        getOptionLabel: (option) => (option === null || option === void 0 ? void 0 : option.full_address) || (option === null || option === void 0 ? void 0 : option.location) || '', filterOptions: (x) => x, autoComplete: true, includeInputInList: true, value: value || null, selectOnFocus: true, handleHomeEndKeys: true, disabled: disabled, noOptionsText: _jsx(FormattedMessage, { id: "ui.locationAutocomplete.empty", defaultMessage: "ui.locationAutocomplete.empty" }), onChange: handleChange, onInputChange: handleSearch, isOptionEqualToValue: (option, value) => value.lat === option.lat && value.lng === option.lng, renderInput: (params) => {
            return (_jsx(TextField, Object.assign({}, params, TextFieldProps, { margin: "dense", InputProps: Object.assign(Object.assign({}, params.InputProps), { autoComplete: 'location', endAdornment: (_jsxs(React.Fragment, { children: [isLoading ? _jsx(CircularProgress, { color: "inherit", size: 20 }) : null, params.InputProps.endAdornment] })) }) })));
        }, renderOption: (props, option, { inputValue }) => {
            const matches = match(option.full_address, inputValue);
            const parts = parse(option.full_address, matches);
            return (_jsx("li", Object.assign({}, props, { style: { whiteSpace: 'break-spaces' } }, { children: parts.map((part, index) => part.highlight ? (_jsx("span", Object.assign({ style: { fontWeight: 700 } }, { children: part.text }), index)) : (part.text)) }), `${option.lat}_${option.lng}`));
        } }, rest)));
}
