import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import { getSettingsCollection } from "@insite/client-framework/Store/Context/ContextSelectors";
import { GoogleMap, InfoWindow, Marker } from "@react-google-maps/api";
import * as React from "react";
import { connect } from "react-redux";

export interface HasDynamicGoogleMaps {
    useLoadScript: ({ googleMapsApiKey }: { googleMapsApiKey: any }) => { isLoaded: boolean };
    GoogleMap: GoogleMap;
    InfoWindow: InfoWindow;
    Marker: Marker;
}

export default function withDynamicGoogleMaps(Component: React.ComponentType<any>) {
    return function passPropsOn(props: any) {
        return <ImportGoogleMapsConnected {...props} component={Component} />;
    };
}

class ImportGoogleMaps extends React.Component {
    state = {
        useLoadScript: () => ({ isLoaded: false }),
        GoogleMap: null,
        InfoWindow: null,
        Marker: null,
    };

    componentDidMount() {
        if ((this.props as any).disableGoogleScriptsInclusion) {
            return;
        }

        import(/* webpackChunkName: "googleMapsApi" */ "@react-google-maps/api").then(
            ({ useLoadScript, GoogleMap, InfoWindow, Marker }) => {
                this.setState({
                    useLoadScript,
                    GoogleMap,
                    InfoWindow,
                    Marker,
                });
            },
        );
    }

    render() {
        const { component: Component, disableGoogleScriptsInclusion } = this.props as any;
        if (
            !disableGoogleScriptsInclusion &&
            (!this.state.useLoadScript || !this.state.GoogleMap || !this.state.InfoWindow || !this.state.Marker)
        ) {
            return null;
        }

        return <Component {...this.props} {...this.state} />;
    }
}

const mapStateToProps = (state: ApplicationState) => ({
    disableGoogleScriptsInclusion: getSettingsCollection(state).websiteSettings.disableGoogleScriptsInclusion,
});

const ImportGoogleMapsConnected = connect(mapStateToProps)(ImportGoogleMaps);
