import { __awaiter } from "tslib";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } 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 { useLoadScript } from '@react-google-maps/api';
import { SCPreferences, useSCContext, useSCPreferences, useSCUser } from '@selfcommunity/react-core';
import { SCCommunitySubscriptionTier, SCEventLocationType } from '@selfcommunity/types';
import axios from 'axios';
import classNames from 'classnames';
import { useEffect, useMemo, useState } from 'react';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import UrlTextField from '../../shared/UrlTextField';
import { PREFIX } from './constants';
import LiveStream from '../LiveStream';
import LiveStreamFormSettings from '../LiveStreamForm/LiveStreamFormSettings';
import { SCLiveStreamTemplateType } from '../../types/liveStream';
import { LIVESTREAM_DEFAULT_SETTINGS } from '../LiveStreamForm/constants';
import { getNewDate } from './utils';
const messages = defineMessages({
    virtualPlaceholder: {
        id: 'ui.eventForm.address.online.placeholder',
        defaultMessage: 'ui.eventForm.address.online.placeholder'
    },
    name: {
        id: 'ui.eventForm.name.placeholder',
        defaultMessage: 'ui.eventForm.name.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) {
    var _a, _b;
    //PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    // INTL
    const intl = useIntl();
    // PROPS
    const { className, locations = [SCEventLocationType.PERSON, SCEventLocationType.ONLINE, SCEventLocationType.LIVESTREAM], event, forwardGeolocationData, forwardLivestreamSettingsData } = props;
    // STATE
    const [location, setLocation] = useState((event === null || event === void 0 ? void 0 : event.location) || locations[0]);
    const [geolocation, setGeoLocation] = useState(event ? { description: event.geolocation } : null);
    const [inputValue, setInputValue] = useState('');
    const [suggestions, setSuggestions] = useState([]);
    const [timeoutId, setTimeoutId] = useState(null);
    const liveStream = useMemo(() => {
        return (event.live_stream ||
            {
                title: (event === null || event === void 0 ? void 0 : event.name) || `${intl.formatMessage(messages.name)}`,
                created_at: (event === null || event === void 0 ? void 0 : event.start_date) || getNewDate(),
                settings: LIVESTREAM_DEFAULT_SETTINGS
            });
    }, [event]);
    // CONTEXT
    const scContext = useSCContext();
    const scUserContext = useSCUser();
    const { preferences } = useSCPreferences();
    const geocodingApiKey = useMemo(() => scContext.settings.integrations && scContext.settings.integrations.geocoding.apiKey, [scContext.settings.integrations]);
    const { isLoaded } = useLoadScript({
        googleMapsApiKey: scContext.settings.integrations.geocoding.apiKey,
        libraries: ['places', 'geocoding']
    });
    const isFreeTrialTier = useMemo(() => preferences &&
        SCPreferences.CONFIGURATIONS_SUBSCRIPTION_TIER in preferences &&
        preferences[SCPreferences.CONFIGURATIONS_SUBSCRIPTION_TIER].value &&
        preferences[SCPreferences.CONFIGURATIONS_SUBSCRIPTION_TIER].value === SCCommunitySubscriptionTier.FREE_TRIAL, [preferences]);
    const canViewLiveTab = useMemo(() => {
        var _a, _b;
        return (!isFreeTrialTier || (isFreeTrialTier && (scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) && (scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user.id) === 1)) &&
            (((_b = (_a = scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.create_live_stream) || event.live_stream);
    }, [(_a = scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) === null || _a === void 0 ? void 0 : _a.permission, event]);
    const isInPersonTabActive = useMemo(() => locations.includes(SCEventLocationType.PERSON) || event.location === SCEventLocationType.PERSON, [locations]);
    const isOnlineTabActive = useMemo(() => locations.includes(SCEventLocationType.ONLINE) || event.location === SCEventLocationType.ONLINE, [locations]);
    const isLiveTabActive = useMemo(() => {
        var _a, _b;
        return locations.includes(SCEventLocationType.LIVESTREAM) &&
            (!isFreeTrialTier || (isFreeTrialTier && (scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) && (scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user.id) === 1)) &&
            (((_b = (_a = scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.create_live_stream) || event.live_stream);
    }, [(_b = scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) === null || _b === void 0 ? void 0 : _b.permission, event]);
    // HANDLERS
    const handleChange = (_event, newValue) => {
        setLocation(newValue);
        forwardGeolocationData({ location: 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: 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 });
    };
    const handleLiveStreamSettingsChange = (settings) => {
        forwardLivestreamSettingsData(settings);
    };
    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 null;
    }
    if (!isInPersonTabActive && !isOnlineTabActive && !isLiveTabActive) {
        return null;
    }
    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: [isInPersonTabActive && (_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" }) })), isOnlineTabActive && (_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" }) })), isLiveTabActive && canViewLiveTab && (_jsx(Tab, { value: SCEventLocationType.LIVESTREAM, classes: { root: classes.tab }, icon: _jsx(Icon, { children: "photo_camera" }), iconPosition: "start", label: _jsx(_Fragment, { children: _jsx(FormattedMessage, { id: "ui.eventForm.address.liveStream.label", defaultMessage: "ui.eventForm.address.liveStream.label" }) }) }))] })), _jsxs(Box, Object.assign({ className: classes.tabContent }, { children: [isInPersonTabActive && location === SCEventLocationType.PERSON && (_jsx(Autocomplete, { 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] })) }) }))) })), isOnlineTabActive && 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 })), isLiveTabActive && canViewLiveTab && location === SCEventLocationType.LIVESTREAM && (_jsxs(_Fragment, { children: [_jsx(LiveStream, { template: SCLiveStreamTemplateType.SNIPPET, liveStream: liveStream, actions: _jsx(_Fragment, {}) }), _jsx(LiveStreamFormSettings, { settings: liveStream.settings || LIVESTREAM_DEFAULT_SETTINGS, onChange: handleLiveStreamSettingsChange })] }))] }))] })));
}
