import { __awaiter } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Autocomplete, Box, InputAdornment, Tab, Tabs, TextField } from '@mui/material';
import Icon from '@mui/material/Icon';
import { styled } from '@mui/material/styles';
import { useThemeProps } from '@mui/system';
import { SCEventLocationType } from '@selfcommunity/types';
import axios from 'axios';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import HiddenPlaceholder from '../../shared/HiddenPlaceholder';
import UrlTextField from '../../shared/UrlTextField';
import { PREFIX } from './constants';
import { useSCGoogleApiLoader } from '@selfcommunity/react-core';
const messages = defineMessages({
    virtualPlaceholder: {
        id: 'ui.eventForm.address.online.placeholder',
        defaultMessage: 'ui.eventForm.address.online.placeholder'
    }
});
const classes = {
    root: `${PREFIX}-event-address-root`,
    tabs: `${PREFIX}-event-address-tabs`,
    tab: `${PREFIX}-event-address-tab`,
    tabContent: `${PREFIX}-event-address-tab-content`
};
const Root = styled(Box, {
    name: PREFIX,
    slot: 'EventAddressRoot'
})(() => ({}));
export default function EventAddress(inProps) {
    //PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    // INTL
    const intl = useIntl();
    // PROPS
    const { className, forwardGeolocationData, event } = props;
    // STATE
    const [location, setLocation] = useState((event === null || event === void 0 ? void 0 : event.location) || SCEventLocationType.PERSON);
    const [geolocation, setGeoLocation] = useState(event ? { description: event.geolocation } : null);
    const [inputValue, setInputValue] = useState('');
    const [suggestions, setSuggestions] = useState([]);
    const [timeoutId, setTimeoutId] = useState(null);
    // HOOKS
    const { isLoaded, geocodingApiKey } = useSCGoogleApiLoader();
    // HANDLERS
    const handleChange = (_event, newValue) => {
        setLocation(newValue);
    };
    const handleSelection = (_event, newValue) => __awaiter(this, void 0, void 0, function* () {
        if (newValue) {
            try {
                const response = yield axios.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: newValue.description.split(',')[0] + '. ' + 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 });
    };
    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 _jsx(HiddenPlaceholder, {});
    }
    return (_jsxs(Root, Object.assign({ className: classNames(classes.root, className) }, { children: [_jsxs(Tabs, Object.assign({ className: classes.tabs, value: location, onChange: handleChange, indicatorColor: "secondary", textColor: "secondary", variant: "fullWidth" }, { children: [_jsx(Tab, { value: SCEventLocationType.PERSON, classes: { root: classes.tab }, icon: _jsx(Icon, { children: "add_location_alt" }), iconPosition: "start", label: _jsx(FormattedMessage, { id: "ui.eventForm.address.live.label", defaultMessage: "ui.eventForm.address.live.label" }) }), _jsx(Tab, { value: SCEventLocationType.ONLINE, classes: { root: classes.tab }, icon: _jsx(Icon, { children: "play_circle_outline" }), iconPosition: "start", label: _jsx(FormattedMessage, { id: "ui.eventForm.address.online.label", defaultMessage: "ui.eventForm.address.online.label" }) })] })), _jsxs(Box, Object.assign({ className: classes.tabContent }, { children: [location === SCEventLocationType.PERSON && (_jsx(Autocomplete, { disabled: !geocodingApiKey, size: "small", value: geolocation, onChange: handleSelection, inputValue: inputValue, onInputChange: handleLocationChange, options: suggestions, getOptionLabel: (option) => option.description || geolocation.description, noOptionsText: _jsx(FormattedMessage, { id: "ui.eventForm.address.live.noResults", defaultMessage: "ui.eventForm.address.live.noResults" }), isOptionEqualToValue: (option, value) => option.description === value.description, renderInput: (params) => (_jsx(TextField, Object.assign({}, params, { label: _jsx(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: (_jsxs(_Fragment, { children: [_jsx(InputAdornment, Object.assign({ position: "start" }, { children: _jsx(Icon, { children: "add_location_alt" }) })), params.InputProps.endAdornment] })) }) }))) })), location === SCEventLocationType.ONLINE && (_jsx(UrlTextField, { size: "small", fullWidth: true, type: "url", placeholder: `${intl.formatMessage(messages.virtualPlaceholder)}`, helperText: _jsx(FormattedMessage, { id: "ui.eventForm.address.online.help", defaultMessage: "ui.eventForm.address.online.help" }), InputProps: {
                            endAdornment: _jsx(Icon, { children: "play_circle_outline" })
                        }, onChange: handleLinkChange }))] }))] })));
}
