"use client"
import React, { useEffect } from 'react'
import { MapContainer, TileLayer, useMap } from 'react-leaflet'
import "leaflet/dist/leaflet.css";
import { useGlobalContext } from '@/app/context/globalContext';


function FlyToActiveCity({activeCityCords}){
    const map  = useMap();

    useEffect(() => {
        if(activeCityCords){
            const zoomLevel = 13;
            const flyToOption = {
                duration: 2,
            };
            map.flyTo([activeCityCords.lat, activeCityCords.lon], zoomLevel, flyToOption); 
        }
    }, [activeCityCords, map]);
    return null;
}


const MapApp = () => {
    const {forecast} = useGlobalContext();
    const activeCityCords = forecast?.coord;
    if(!forecast || !forecast.coord || !activeCityCords){
        return (
        <div>
            <h1>Loading...</h1>
        </div>
        );
    }


  return (
    <div className='flex-1 basis-[50%] border col-span-4 rounded-lg h-[20rem]'>
        <MapContainer center={[activeCityCords.lat, activeCityCords.lon]} zoom = {13} scrollWheelZoom = {false} style = {{height: "calc(100% - 2rem)", width: "calc(100% - 2rem)"}} className='rounded-lg m-4'>
            <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'/>
            <FlyToActiveCity activeCityCords={activeCityCords}/>
        </MapContainer>
    </div>
  )
}

export default MapApp