import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { FiPlus, FiArrowRight } from 'react-icons/fi';
import { GoogleMap, useJsApiLoader, Marker, InfoWindow } from '@react-google-maps/api';

import '../styles/orphanages.css';
import MapMarker from '../images/map_marker.svg';
import api from '../services/api';

interface Orphanage {
  id: number;
  latitude: number;
  longitude: number;
  name: string;
}

const containerStyle = {
  width: '100%',
  height: '100%'
};

const center = {
  lat: -23.9550537,
  lng: -46.3204442
};

function OrphanagesMap() {
  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: process.env.REACT_APP_MAPS_API_KEY!
  });

  const [orphanages, setOrphanages] = useState<Orphanage[]>([]);
  const [selectedOrphanage, setSelectedOrphanage] = useState<Orphanage | null>(null);

  useEffect(() => {
    api.get('orphanages').then(response => {
      setOrphanages(response.data);
    });
  }, []);

  if (!isLoaded) {
    return <div>Loading Map...</div>;
  }

  return (
    <div id="page-map">
      <aside>
        <header>
          <img src={MapMarker} alt="Happy"/>
          <h1>Escolha um orfanato no mapa</h1>
          <p>Muitas crianças estão esperando a sua visita! :)</p>
        </header>
        <footer>
          <strong>Santos</strong>
          <span>São Paulo</span>
        </footer>
      </aside>
      
      <GoogleMap
        key={process.env.REACT_APP_MAPS_API_KEY!}     
        mapContainerStyle={containerStyle}
        center={center}
        zoom={14}
        options={{
            disableDefaultUI: true,
            zoomControl: true,
            zoomControlOptions: {
                position: window.google.maps.ControlPosition.TOP_LEFT
            },
        }}
        onClick={() => setSelectedOrphanage(null)}
      >
        {orphanages.map(orphanage => (
          <Marker
            key={orphanage.id}
            position={{ lat: orphanage.latitude, lng: orphanage.longitude }}
            icon={{
              url: MapMarker,
              scaledSize: new window.google.maps.Size(58, 68)
            }}
            onClick={() => {
              setSelectedOrphanage(orphanage);
            }}
          />
        ))}

        {selectedOrphanage && (
          <InfoWindow
            position={{ lat: selectedOrphanage.latitude, lng: selectedOrphanage.longitude }}
            onCloseClick={() => {
              setSelectedOrphanage(null);
            }}
          >
            <div className="map-popup">
              {selectedOrphanage.name}
              <Link to={`/orphanage/${selectedOrphanage.id}`}>
                <FiArrowRight size={20} color="#FFF"></FiArrowRight>
              </Link>
            </div>
          </InfoWindow>
        )}
      </GoogleMap>

      <Link to="/orphanages/create" className="create-orphanage">
        <FiPlus size="32" color="#FFF"></FiPlus>
      </Link>
    </div>
  );
}

export default OrphanagesMap;