import { useEffect, useRef } from 'react';

declare global {
    interface Window {
        mapboxgl: any;
        MapboxGeocoder: any;
    }
}

interface Props {
    value?: {
        lat: number;
        lng: number;
        address: string;
    };

    onChange: (data: { lat: number; lng: number; address: string }) => void;
}

export default function MapPicker({ value, onChange }: Props) {
    const mapRef = useRef<HTMLDivElement | null>(null);

    useEffect(() => {
        if (!mapRef.current) return;

        const mapboxgl = window.mapboxgl;

        mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_TOKEN;

        const map = new mapboxgl.Map({
            container: mapRef.current,
            style: 'mapbox://styles/mapbox/streets-v12',
            center: value ? [value.lng, value.lat] : [27.5615, 53.9045],
            zoom: value ? 14 : 10,
        });

        const popup = new mapboxgl.Popup({
            offset: 25,
            closeButton: false,
            className: 'sport-popup',
        }).setHTML(`
            <div class="overflow-hidden rounded-2xl">
                <img
                    src="https://images.unsplash.com/photo-1518611012118-696072aa579a"
                    class="h-32 w-full object-cover"
                />

                <div class="p-4">
                    <div class="mb-1 flex items-center justify-between">
                        <h3 class="text-sm font-semibold">
                            Спортивный клуб
                        </h3>

                        <span class="rounded-full bg-green-100 px-2 py-1 text-[10px] font-medium text-green-700">
                            Открыто
                        </span>
                    </div>

                    <p class="text-xs text-gray-500">
                        Йога • Пилатес • Стретчинг
                    </p>

                    <p class="mt-2 text-xs text-gray-400">
                        Выберите точное расположение клуба
                    </p>
                </div>
            </div>
        `);

        const marker = new mapboxgl.Marker({
            draggable: true,
        }).setPopup(popup);

        if (value) {
            marker.setLngLat([value.lng, value.lat]).addTo(map);
        }

        const geocoder = new window.MapboxGeocoder({
            accessToken: mapboxgl.accessToken,
            mapboxgl,
            marker: false,
            placeholder: 'Введите адрес клуба',
        });

        map.addControl(geocoder);

        geocoder.on('result', (e: any) => {
            const coords = e.result.center;

            marker.setLngLat(coords).addTo(map);

            marker.togglePopup();

            map.flyTo({
                center: coords,
                zoom: 15,
            });

            onChange({
                lng: coords[0],
                lat: coords[1],
                address: e.result.place_name,
            });
        });

        marker.on('dragend', () => {
            const lngLat = marker.getLngLat();

            onChange({
                lat: lngLat.lat,
                lng: lngLat.lng,
                address: '',
            });
        });

        return () => map.remove();
    }, []);

    return (
        <div className="overflow-hidden rounded-3xl border shadow-sm">
            <div ref={mapRef} className="h-[450px] w-full" />
        </div>
    );
}
