/*
 * Block libraries
 */
const {__} = wp.i18n;
// Get registerBlockType and Editable from wp.blocks
const {registerBlockType} = wp.blocks;
const {PanelBody, ToggleControl} = wp.components;
const {Component, createElement, Fragment} = wp.element;
const {InspectorControls} = wp.editor;
const hasMultipleLocations = yoastSeoLocal.hasMultipleLocations;

import Select from 'react-select';

class yoastSeoLocalMap extends Component {
    static getInitialState(selectedLocation) {
        return {
            locations: [],
            selectedLocation: selectedLocation,
            options: [],
        }
    }

    constructor() {
        // Get all arguments from parent class.
        super(...arguments);

        // Maybe we have a previously selected post. Try to load it.
        this.state = this.constructor.getInitialState(this.props.attributes.selectedLocation);

        // Bind so we can use 'this' inside the method.
        this.getOptions = this.getOptions.bind(this);
        this.updateLocation = this.updateLocation.bind(this);
    }

    componentDidMount() {
        const {attributes} = this.props;

        if (!hasMultipleLocations) {
            this.updateLocation();
        } else {
            this.getOptions();
        }

        if (attributes.selectedLocation) {
            this.updateLocation(attributes.selectedLocation);
            this.setState({output: '<img src="' + yoastSeoLocal.plugin_url + 'images/map-placeholder.jpg">'});
        } else {
            if (hasMultipleLocations) {
                this.setState({output: __('Please select a location.')});
            } else {
                this.setState({output: '<img src="' + yoastSeoLocal.plugin_url + 'images/map-placeholder.jpg">'});
            }
        }
    }

    /**
     * Loading Locations.
     */
    getOptions() {
        wpseoApi.get("wpseo_locations", (locations) => {
            let options = {};
            locations.forEach((location) => {
                options[location.ID] = {value: location.ID, label: location.label};
            });
            options['all'] = {value: 'all', label: __( 'Show all locations' )};
            this.setState({options});
        });
    }

    updateLocation() {
        const {
            attributes: {
                showState,
                showCountry,
                showPhone,
                showPhone2nd,
                showFax,
                showEmail,
                showURL,
                allowScrolling,
                allowDragging,
                defaultShowInfoWindow,
                mapType,
                zoomLevel,
                mapWidth,
                mapHeight,
                showCategoryFilter,
                showRoute,
            },
            attributes,
            setAttributes
        } = this.props;

        const {selectedLocation} = (hasMultipleLocations ? this.state : '');

        if (hasMultipleLocations && selectedLocation !== attributes.selectedLocation) {
            setAttributes({selectedLocation});
            this.setState({selectedLocation});
        }

        if( selectedLocation ) {
            this.setState({output: '<img src="' + yoastSeoLocal.plugin_url + 'images/map-placeholder.jpg">'});
        }

        setAttributes({showState});
        setAttributes({showCountry});
        setAttributes({showPhone});
        setAttributes({showPhone2nd});
        setAttributes({showFax});
        setAttributes({showEmail});
        setAttributes({showURL});
        setAttributes({allowScrolling});
        setAttributes({allowDragging});
        setAttributes({defaultShowInfoWindow});
        setAttributes({mapType});
        setAttributes({zoomLevel});
        setAttributes({mapWidth});
        setAttributes({mapHeight});
        setAttributes({showCategoryFilter});
        setAttributes({showRoute});

        /*
        jQuery.ajax({
            type: 'post',
            dataType: 'json',
            url: yoastSeoLocal.ajax_url,
            data: {
                action: 'wpseo_local_show_map_ajax_cb',
                id: selectedLocation,
                hideName: hideName,
                hideCompanyAddress: hideCompanyAddress,
                showOnOneLine: showOnOneLine,
                showState: showState,
                showCountry: showCountry,
                showPhone: showPhone,
                showPhone2nd: showPhone2nd,
                showFax: showFax,
                showEmail: showEmail,
                showURL: showURL,
            },
            success: (function (response) {
                this.setState({output: response});
            }).bind(this),
            error: function (error) {
                console.log(error)
            }
        }); */
    }

    /**
     * Render output to screen.
     */
    render() {
        const {
            attributes: {
                showState,
                showCountry,
                showPhone,
                showPhone2nd,
                showFax,
                showEmail,
                showURL,
                allowScrolling,
                allowDragging,
                defaultShowInfoWindow,
                mapType,
                zoomLevel,
                mapWidth,
                mapHeight,
                showCategoryFilter,
                showRoute,
            },
            setAttributes,
        } = this.props;

        const {selectedLocation} = this.state;

        return [
            // If we are focused on this block, create the inspector controls.
            <Fragment key='fragment'>
                <InspectorControls key='inspector'>
                    <PanelBody title={__('Yoast Local SEO Address Settings')}>
                        {this.state.options && hasMultipleLocations
                            ? <Select
                                // Selected value.
                                value={this.state.options[selectedLocation]}
                                options={Object.values(this.state.options)}
                                placeholder={__('Please select a location')}
                                onChange={({value}) =>
                                    this.setState({selectedLocation: value}, this.updateLocation)
                                }/>
                            : <span>{__('Loading locations')}</span>
                        }
                        <section className="yoast-seo-local__maptype">
                            <div className="yoast-seo-local__maptype__radio">
                                <input type="radio" value="roadmap" id="roadmap"
                                       checked={mapType === 'roadmap'}
                                       onChange={(e) => {
                                           setAttributes({mapType: e.target.value});
                                           this.setState({mapType: e.target.value}, this.updateLocation);
                                       }}
                                />
                                <label htmlFor="roadmap">
                                    <img src={yoastSeoLocal.plugin_url + 'images/map-roadmap.png'}/>
                                    <span>{__('Roadmap')}</span>
                                </label>
                            </div>
                            <div className="yoast-seo-local__maptype__radio">
                                <input type="radio" value="hybrid" id="hybrid"
                                       checked={mapType === 'hybrid'}
                                       onChange={(e) => {
                                           setAttributes({mapType: e.target.value});
                                           this.setState({mapType: e.target.value}, this.updateLocation);
                                       }}
                                />
                                <label htmlFor="hybrid">
                                    <img src={yoastSeoLocal.plugin_url + 'images/map-hybrid.png'}/>
                                    <span>{__('Hybrid')}</span>
                                </label>
                            </div>
                            <div className="yoast-seo-local__maptype__radio">
                                <input type="radio" value="satellite" id="satellite"
                                       checked={mapType === 'satellite'}
                                       onChange={(e) => {
                                           setAttributes({mapType: e.target.value});
                                           this.setState({mapType: e.target.value}, this.updateLocation);
                                       }}
                                />
                                <label htmlFor="satellite">
                                    <img src={yoastSeoLocal.plugin_url + 'images/map-satellite.png'}/>
                                    <span>{__('Satellite')}</span>
                                </label>
                            </div>
                            <div className="yoast-seo-local__maptype__radio">
                                <input type="radio" value="terrain" id="terrain"
                                       checked={mapType === 'terrain'}
                                       onChange={(e) => {
                                           setAttributes({mapType: e.target.value});
                                           this.setState({mapType: e.target.value}, this.updateLocation);
                                       }}
                                />
                                <label htmlFor="terrain">
                                    <img src={yoastSeoLocal.plugin_url + 'images/map-terrain.png'}/>
                                    <span>{__('Terrain')}</span>
                                </label>
                            </div>
                        </section>
                        <section className="yoast-seo-local__mapdimensions">
                            <label htmlFor="mapwidth">{__('Width')}</label>
                            <input
                                type="number"
                                step="1"
                                min="1"
                                value={mapWidth}
                                id="mapwidth"
                                onChange={(e) => {
                                    setAttributes({mapWidth: e.target.value});
                                    this.setState({mapWidth: e.target.value}, this.updateLocation);
                                }}/>
                            <label htmlFor="mapheight">{__('Height')}</label>
                            <input
                                type="number"
                                step="1"
                                min="1"
                                value={mapHeight}
                                id="mapheight"
                                onChange={(e) => {
                                    setAttributes({mapHeight: e.target.value});
                                    this.setState({mapHeight: e.target.value}, this.updateLocation);
                                }}/>
                        </section>
                        <label htmlFor="zoomlevel">Zoomlevel</label>
                        <select
                            id="zoomlevel"
                            value={zoomLevel}
                            onChange={(e) => {
                                setAttributes({zoomLevel: e.target.value});
                                this.setState({zoomLevel: e.target.value}, this.updateLocation);
                            }}>
                            <option value="-1">Auto</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                            <option value="10">10</option>
                            <option value="11">11</option>
                            <option value="12">12</option>
                        </select>
                        <ToggleControl
                            label={__('Allow scrolling of map')}
                            checked={allowScrolling}
                            onChange={() => {
                                setAttributes({allowScrolling: !allowScrolling});
                                this.setState({allowScrolling: !allowScrolling}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Allow dragging of map')}
                            checked={allowDragging}
                            onChange={() => {
                                setAttributes({allowDragging: !allowDragging});
                                this.setState({allowDragging: !allowDragging}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show route planner')}
                            checked={showRoute}
                            onChange={() => {
                                setAttributes({showRoute: !showRoute});
                                this.setState({showRoute: !showRoute}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show state')}
                            checked={showState}
                            onChange={() => {
                                setAttributes({showState: !showState});
                                this.setState({showState: !showState}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show country')}
                            checked={showCountry}
                            onChange={() => {
                                setAttributes({showCountry: !showCountry});
                                this.setState({showCountry: !showCountry}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show phone number')}
                            checked={showPhone}
                            onChange={() => {
                                setAttributes({showPhone: !showPhone});
                                this.setState({showPhone: !showPhone}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show second phone number')}
                            checked={showPhone2nd}
                            onChange={() => {
                                setAttributes({showPhone2nd: !showPhone2nd});
                                this.setState({showPhone2nd: !showPhone2nd}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show fax number')}
                            checked={showFax}
                            onChange={() => {
                                setAttributes({showFax: !showFax});
                                this.setState({showFax: !showFax}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show e-mail address')}
                            checked={showEmail}
                            onChange={() => {
                                setAttributes({showEmail: !showEmail});
                                this.setState({showEmail: !showEmail}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show URL')}
                            checked={showURL}
                            onChange={() => {
                                setAttributes({showURL: !showURL});
                                this.setState({showURL: !showURL}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show infowindow by default')}
                            checked={defaultShowInfoWindow}
                            onChange={() => {
                                setAttributes({defaultShowInfoWindow: !defaultShowInfoWindow});
                                this.setState({defaultShowInfoWindow: !defaultShowInfoWindow}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show category filter under map')}
                            checked={showCategoryFilter}
                            onChange={() => {
                                setAttributes({showCategoryFilter: !showCategoryFilter});
                                this.setState({showCategoryFilter: !showCategoryFilter}, this.updateLocation);
                            }}
                        />
                    </PanelBody>
                </InspectorControls>
                <div dangerouslySetInnerHTML={{__html: this.state.output}}/>
            </Fragment>
        ]
    }
}

/**
 * Register example block
 */
registerBlockType(
    'yoast-seo-local/map',
    {
        title: 'Yoast SEO: Local - ' + __('Map'),
        category: 'common',
        icon: 'location-alt',
        keywords: [
            __('Address'),
            __('Yoast'),
            __('Local'),
        ],
        attributes: {
            selectedLocation: {
                type: 'number',
                default: 0,
            },
            showState: {
                type: 'boolean',
                default: false
            },
            showCountry: {
                type: 'boolean',
                default: false
            },
            showPhone: {
                type: 'boolean',
                default: true
            },
            showPhone2nd: {
                type: 'boolean',
                default: true
            },
            showFax: {
                type: 'boolean',
                default: true
            },
            showEmail: {
                type: 'boolean',
                default: false
            },
            showURL: {
                type: 'boolean',
                default: false
            },
            showRoute: {
                type: 'boolean',
                default: false
            },
            allowScrolling: {
                type: 'boolean',
                default: true
            },
            allowDragging: {
                type: 'boolean',
                default: true
            },
            markerClustering: {
                type: 'boolean',
                default: false
            },
            defaultShowInfoWindow: {
                type: 'boolean',
                default: false
            },
            mapType: {
                type: 'string',
                default: 'roadmap'
            },
            zoomLevel: {
                type: 'string',
                default: '-1'
            },
            mapWidth: {
                type: 'string',
                default: '400'
            },
            mapHeight: {
                type: 'string',
                default: '300'
            },
            showCategoryFilter: {
                type: 'bolean',
                default: false
            }
        },
        edit: (yoastSeoLocalMap),
        save(props) {
            const {attributes} = props;
            let shortcode = [];

            if( attributes.selectedLocation ) {
                shortcode.push('id="' + attributes.selectedLocation + '"');
            }

            shortcode.push('width="' + attributes.mapWidth + '"');
            shortcode.push('height="' + attributes.mapHeight + '"');
            shortcode.push('zoom="' + attributes.zoomLevel + '"');
            shortcode.push('map_style="' + attributes.mapType + '"');
            shortcode.push('scrollable="' + attributes.allowScrolling + '"');
            shortcode.push('draggable="' + attributes.allowDragging + '"');
            shortcode.push('show_route="' + attributes.showRoute + '"');
            shortcode.push('show_state="' + attributes.showState + '"');
            shortcode.push('show_country="' + attributes.showCountry + '"');
            shortcode.push('show_url="' + attributes.showURL + '"');
            shortcode.push('show_email="' + attributes.showEmail + '"');
            shortcode.push('show_category_filter="' + attributes.showCategoryFilter + '"');
            shortcode.push('default_show_infowindow="' + attributes.defaultShowInfoWindow + '"');
            shortcode.push('show_phone="' + attributes.showPhone + '"');
            shortcode.push('show_phone_2="' + attributes.showPhone2nd + '"');
            shortcode.push('show_fax="' + attributes.showFax + '"');

            return (
                <div className={props.className}>
                    [wpseo_map { shortcode.join(' ') } ]
                </div>
            )
        }
    },
);
