"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 styles_1 = require("@mui/material/styles");
const system_1 = require("@mui/system");
const api_1 = require("@react-google-maps/api");
const types_1 = require("@selfcommunity/types");
const axios_1 = tslib_1.__importDefault(require("axios"));
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const react_1 = require("react");
const react_intl_1 = require("react-intl");
const HiddenPlaceholder_1 = tslib_1.__importDefault(require("../../shared/HiddenPlaceholder"));
const UrlTextField_1 = tslib_1.__importDefault(require("../../shared/UrlTextField"));
const constants_1 = require("./constants");
const react_core_1 = require("@selfcommunity/react-core");
const messages = (0, react_intl_1.defineMessages)({
    virtualPlaceholder: {
        id: 'ui.eventForm.address.online.placeholder',
        defaultMessage: 'ui.eventForm.address.online.placeholder'
    }
});
const classes = {
    root: `${constants_1.PREFIX}-event-address-root`,
    tabs: `${constants_1.PREFIX}-event-address-tabs`,
    tab: `${constants_1.PREFIX}-event-address-tab`,
    tabContent: `${constants_1.PREFIX}-event-address-tab-content`
};
const Root = (0, styles_1.styled)(material_1.Box, {
    name: constants_1.PREFIX,
    slot: 'EventAddressRoot'
})(() => ({}));
function EventAddress(inProps) {
    //PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    // INTL
    const intl = (0, react_intl_1.useIntl)();
    // PROPS
    const { className, forwardGeolocationData, event } = props;
    // STATE
    const [location, setLocation] = (0, react_1.useState)((event === null || event === void 0 ? void 0 : event.location) || types_1.SCEventLocationType.PERSON);
    const [geolocation, setGeoLocation] = (0, react_1.useState)(event ? { description: event.geolocation } : null);
    const [inputValue, setInputValue] = (0, react_1.useState)('');
    const [suggestions, setSuggestions] = (0, react_1.useState)([]);
    const [timeoutId, setTimeoutId] = (0, react_1.useState)(null);
    // PREFERENCES
    const { preferences } = (0, react_core_1.useSCPreferences)();
    // MEMO
    const geocodingApiKey = (0, react_1.useMemo)(() => {
        return preferences && react_core_1.SCPreferences.PROVIDERS_GOOGLE_GEOCODING_API_KEY in preferences
            ? preferences[react_core_1.SCPreferences.PROVIDERS_GOOGLE_GEOCODING_API_KEY].value
            : null;
    }, [preferences]);
    const { isLoaded } = (0, api_1.useLoadScript)({
        googleMapsApiKey: geocodingApiKey,
        libraries: ['places', 'geocoding']
    });
    // HANDLERS
    const handleChange = (_event, newValue) => {
        setLocation(newValue);
    };
    const handleSelection = (_event, newValue) => tslib_1.__awaiter(this, void 0, void 0, function* () {
        if (newValue) {
            try {
                const response = yield axios_1.default.get(`https://maps.googleapis.com/maps/api/geocode/json`, {
                    params: {
                        place_id: newValue.id,
                        key: geocodingApiKey
                    }
                });
                const place = response.data.results[0];
                setGeoLocation(newValue);
                forwardGeolocationData({
                    location,
                    geolocation: place.formatted_address,
                    lat: place.geometry.location.lat,
                    lng: place.geometry.location.lng
                });
            }
            catch (error) {
                console.error('Error fetching place details:', error);
            }
        }
    });
    const handleLocationChange = (_event, newInputValue) => {
        setInputValue(newInputValue);
    };
    const handleLinkChange = (event) => {
        forwardGeolocationData({ location, link: event.target.value });
    };
    (0, react_1.useEffect)(() => {
        if (timeoutId) {
            clearTimeout(timeoutId);
        }
        if (inputValue === '') {
            setSuggestions([]);
            return;
        }
        if (inputValue.length >= 3) {
            const newTimeoutId = setTimeout(() => {
                const autocompleteService = new window.google.maps.places.AutocompleteService();
                autocompleteService.getPlacePredictions({ input: inputValue }, (predictions, status) => {
                    if (status === window.google.maps.places.PlacesServiceStatus.OK && predictions) {
                        setSuggestions(predictions.map((prediction) => ({
                            description: prediction.description,
                            id: prediction.place_id
                        })));
                    }
                });
            }, 300);
            setTimeoutId(newTimeoutId);
        }
    }, [inputValue]);
    if (!geocodingApiKey && !isLoaded) {
        return (0, jsx_runtime_1.jsx)(HiddenPlaceholder_1.default, {});
    }
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, { children: [(0, jsx_runtime_1.jsxs)(material_1.Tabs, Object.assign({ className: classes.tabs, value: location, onChange: handleChange, indicatorColor: "secondary", textColor: "secondary", variant: "fullWidth" }, { children: [(0, jsx_runtime_1.jsx)(material_1.Tab, { value: types_1.SCEventLocationType.PERSON, classes: { root: classes.tab }, icon: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "add_location_alt" }), iconPosition: "start", label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventForm.address.live.label", defaultMessage: "ui.eventForm.address.live.label" }) }), (0, jsx_runtime_1.jsx)(material_1.Tab, { value: types_1.SCEventLocationType.ONLINE, classes: { root: classes.tab }, icon: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "play_circle_outline" }), iconPosition: "start", label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventForm.address.online.label", defaultMessage: "ui.eventForm.address.online.label" }) })] })), (0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.tabContent }, { children: [location === types_1.SCEventLocationType.PERSON && ((0, jsx_runtime_1.jsx)(material_1.Autocomplete, { disabled: !geocodingApiKey, size: "small", value: geolocation, onChange: handleSelection, inputValue: inputValue, onInputChange: handleLocationChange, options: suggestions, getOptionLabel: (option) => option.description || geolocation.description, noOptionsText: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventForm.address.live.noResults", defaultMessage: "ui.eventForm.address.live.noResults" }), isOptionEqualToValue: (option, value) => option.description === value.description, renderInput: (params) => ((0, jsx_runtime_1.jsx)(material_1.TextField, Object.assign({}, params, { label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventForm.address.live.placeholder", defaultMessage: "ui.eventForm.address.live.placeholder" }), variant: "outlined", fullWidth: true, InputProps: Object.assign(Object.assign({}, params.InputProps), { endAdornment: ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.InputAdornment, Object.assign({ position: "start" }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "add_location_alt" }) })), params.InputProps.endAdornment] })) }) }))) })), location === types_1.SCEventLocationType.ONLINE && ((0, jsx_runtime_1.jsx)(UrlTextField_1.default, { size: "small", fullWidth: true, type: "url", placeholder: `${intl.formatMessage(messages.virtualPlaceholder)}`, helperText: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventForm.address.online.help", defaultMessage: "ui.eventForm.address.online.help" }), InputProps: {
                            endAdornment: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "play_circle_outline" })
                        }, onChange: handleLinkChange }))] }))] })));
}
exports.default = EventAddress;
