import { MouseEventHandler } from 'react'
import { useMapEvent } from 'react-leaflet'
import { LatLng } from 'leaflet'
import Control from 'react-leaflet-custom-control'

import locateIcon from '../assets/locate.svg'

import styles from '../styles/Map.module.css'
import { SetState } from '../utils/types'
type LocaleButtonProps = {
    setPosition: SetState<LatLng>
}

function LocateButton({ setPosition }: LocaleButtonProps) {
    const map = useMapEvent('locationfound', (e) => {
        setPosition(e.latlng)
        map.flyTo(e.latlng)
    })

    const handleLocale: MouseEventHandler<HTMLAnchorElement> = (e) => {
        e.preventDefault()
        e.stopPropagation()

        map.locate()
    }

    return (
        <Control position='topleft'>
            <div className='leaflet-bar'>
                <a href='#' role='button' onClick={handleLocale}>
                    <img className={styles.localeIcon} src={locateIcon} alt='locate' />
                </a>
            </div>
        </Control>
    )
}

export default LocateButton