import React, { useState, useEffect } from 'react';
import GoogleMapReact from 'google-map-react';
import supercluster from 'points-cluster';

import { config } from 'config/general';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';

// Import actions here

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import find from 'lodash/find';
import styleIdentifiers from './googleMapItem.scss';

// assets
import markerIcon from './assets/marker.svg';
import activeMarkerIcon from './assets/marker-white.svg';
import mapStyle from './assets/style.json';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {
  className?: string;
  markers: [];
  options: {};
  activeMarker: {};
  setActiveMarker: Function;
  onMarkerClick: Function;
}

export type GoogleMapItemProps = StateProps & DispatchProps & OwnProps;

const findMarker = (lat, lng, markers) => {
  return find(markers, marker => {
    const markerLat = marker && marker.place.loc.coordinates[1];
    const markerLng = marker && marker.place.loc.coordinates[0];

    if (markerLat === lat && markerLng === lng) return true;

    return false;
  });
};

const MarkerComponent = marker => {
  const currentMarker = findMarker(marker.lat, marker.lng, marker.markers);

  if (!currentMarker) return '';
  return (
    <div className={styles('marker')} onClick={() => marker.onMarkerClick(currentMarker)}>
      <TextItem path={`${currentMarker.pricingPerHour}€/h`} className={styles('name', 'item')} />
    </div>
  );
};

const ClusterComponent = cluster => {
  return <div className={styles('cluster')}>{cluster.cluster.numPoints}</div>;
};

const GoogleMapItem = (props: GoogleMapItemProps) => {
  const { className, markers, options, activeMarker, setActiveMarker, onMarkerClick } = props;
  const [position, setPosition] = useState();
  const [lastBounds, setLastBounds] = useState();
  // const [center, setCenter] = useState();
  const [clusters, setClusters] = useState();
  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);

  // Allow to dispatch actions
  const dispatch = useDispatch();

  const defaultCenter = { lat: 50.8, lng: 4.3 };

  const getClusters = clustersProps => {
    const markersData = [];

    markers.forEach(function(marker) {
      const lat = marker && marker.place.loc.coordinates[1];
      const lng = marker && marker.place.loc.coordinates[0];

      const obj = {
        lat,
        lng,
        id: marker._id,
      };

      markersData.push(obj);
    });

    const currentClusters = supercluster(markersData, {
      minZoom: 0,
      maxZoom: 14,
      radius: 60,
    });

    return currentClusters(clustersProps);
  };

  const createClusters = ({ currentCenter, zoom, bounds }) => {
    if (bounds) {
      // need it in case of markers update
      setLastBounds(bounds);
      setClusters(getClusters({ center: currentCenter, zoom, bounds }));
    }
  };

  useEffect(() => {
    if (markers && lastBounds && options?.center)
      createClusters({
        currentCenter: options.center,
        zoom: options.zoom || 10,
        bounds: lastBounds,
      });
  }, [markers, options, lastBounds]);

  return (
    <div
      className={styles('google-map-item', className)}
      style={{
        height: options.height || '100%',
        width: options.width || '100%',
      }}
    >
      <GoogleMapReact
        bootstrapURLKeys={{ key: config.googleMapKey }}
        defaultCenter={defaultCenter}
        defaultZoom={options.zoom || 10}
        options={{ styles: mapStyle, ZoomControlOptions: 'BOTTOM_RIGHT' }}
        center={options.center}
        onChange={createClusters}
      >
        {clusters &&
          clusters.length > 0 &&
          clusters.map((cluster, key) => {
            if (cluster.numPoints === 1) {
              return (
                <MarkerComponent
                  lat={cluster.wy}
                  lng={cluster.wx}
                  key={key}
                  activeMarker={activeMarker}
                  action={setActiveMarker}
                  markers={markers}
                  onMarkerClick={onMarkerClick}
                />
              );
            }

            return (
              <ClusterComponent
                lat={cluster.wy}
                lng={cluster.wx}
                points={cluster.points}
                cluster={cluster}
                key={key}
                markers={markers}
              />
            );
          })}
      </GoogleMapReact>
    </div>
  );
};

export default GoogleMapItem;
