import { type FC, useState, useEffect } from 'react'
import { MapContainer, TileLayer, Marker, useMapEvents, useMap } from 'react-leaflet'
import { Icon } from 'leaflet'
import type { LatLngTuple } from 'leaflet'

interface LocationPickerProps {
    initialPosition?: [number, number]
    onLocationSelect: (lat: number, lng: number) => void
}

const ChangeView = ({ center, zoom }: { center: LatLngTuple; zoom: number }) => {
    const map = useMap()
    useEffect(() => {
        map.setView(center, zoom)
    }, [map, center, zoom])
    return null
}

const LocationPicker: FC<LocationPickerProps> = ({ initialPosition, onLocationSelect }) => {
    const [position, setPosition] = useState<LatLngTuple>(
        initialPosition || [35.6892, 51.3890] // تهران به عنوان پیش‌فرض
    )

    useEffect(() => {
        if (initialPosition) {
            setPosition(initialPosition)
        }
    }, [initialPosition])

    const LocationMarker = () => {
        useMapEvents({
            click(e) {
                const newPosition: LatLngTuple = [e.latlng.lat, e.latlng.lng]
                setPosition(newPosition)
                onLocationSelect(newPosition[0], newPosition[1])
            },
        })

        const customIcon = new Icon({
            iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
            iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
            shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
            iconSize: [25, 41],
            iconAnchor: [12, 41],
            popupAnchor: [1, -34],
            shadowSize: [41, 41],
        })

        return position ? <Marker position={position} icon={customIcon} /> : null
    }

    return (
        <div className="w-full h-[400px] rounded-xl overflow-hidden">
            <MapContainer
                center={position}
                zoom={13}
                style={{ height: '100%', width: '100%' }}
                scrollWheelZoom={true}
            >
                <ChangeView center={position} zoom={13} />
                <TileLayer
                    attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <LocationMarker />
            </MapContainer>
        </div>
    )
}

export default LocationPicker

