import {Meteor} from "meteor/meteor";
// @ts-ignore
import {FlowRouter} from 'meteor/ostrio:flow-router-extra';
import React, {FunctionComponent, useEffect, useState} from "react";
import {LocationDocument, LocationValues} from "/imports/api/Listings/both/collections/locations";
import {AdminSearchLocationMap} from "/imports/ui/components/admin/AdminSearchLocationMap";

interface AdminSpacesTagsProps {
    locationId?: string
}

export const AdminLocationEditor: FunctionComponent<AdminSpacesTagsProps> = ({ locationId }) => {

    const [locationState, setLocationState] = useState<LocationValues>({
        name: "",
        polygon: [],
        center: [0,0]
    });

    useEffect(() => {
        if(locationId) {
            Meteor.call("locations.get", locationId, (err: Meteor.Error, location: LocationDocument) => {
                if(!err) {
                    setLocationState({
                        name: location.name,
                        polygon: location.polygon,
                        center: location.center
                    });
                }
            });
        }
    }, [])

    return <div className="grid-container">

        {locationId ?
            <h3 className="margin-top-1 padding-left-1">Edit Location</h3>
            :
            <h3 className="margin-top-1 padding-left-1">New Location</h3>
        }

        <form onSubmit={(evt) => {
            evt.preventDefault();
            if(!locationId) {
                Meteor.call("locations.create", locationState, () => FlowRouter.go("AdminLocations"));
            } else {
                Meteor.call("locations.update", locationId, locationState, () => FlowRouter.go("AdminLocations"));
            }
        }}>
            <input
                className="margin-top-1"
                type="text"
                placeholder="Location Name (Case sensitive)"
                value={locationState.name}
                onChange={(evt) =>
                    setLocationState({ ...locationState, name: evt.target.value })} />

            <AdminSearchLocationMap
                poly={locationState.polygon}
                center={locationState.center}
                onChange={(polygon, center) =>
                    // @ts-ignore
                    setLocationState({ ...locationState, polygon, center })} />

            <button type="submit" className="button margin-top-1">Save</button>
        </form>

    </div>;
}