import { useEffect, useRef, useState } from 'react';
import { Navigation } from 'lucide-react';

// 카카오맵 SDK 키
const KAKAO_MAP_KEY = import.meta.env.VITE_KAKAO_JS_KEY;

// 카카오맵 컴포넌트
function KakaoMap({ lat, lng, name }) {
    const mapRef = useRef(null);
    const [mapLoaded, setMapLoaded] = useState(false);
    const [mapError, setMapError] = useState(false);

    useEffect(() => {
        // API 키가 없으면 에러
        if (!KAKAO_MAP_KEY) {
            setMapError(true);
            return;
        }

        // 카카오맵 SDK 동적 로드
        if (!window.kakao?.maps) {
            const script = document.createElement('script');
            script.src = `//dapi.kakao.com/v2/maps/sdk.js?appkey=${KAKAO_MAP_KEY}&autoload=false`;
            script.onload = () => {
                window.kakao.maps.load(() => setMapLoaded(true));
            };
            script.onerror = () => setMapError(true);
            document.head.appendChild(script);
        } else {
            setMapLoaded(true);
        }
    }, []);

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

        try {
            const position = new window.kakao.maps.LatLng(lat, lng);
            const map = new window.kakao.maps.Map(mapRef.current, {
                center: position,
                level: 3,
            });

            // 마커 추가
            const marker = new window.kakao.maps.Marker({
                position,
                map,
            });

            // 인포윈도우 추가
            if (name) {
                const infowindow = new window.kakao.maps.InfoWindow({
                    content: `<div style="padding:8px 12px;font-size:13px;font-weight:500;">${name}</div>`,
                });
                infowindow.open(map, marker);
            }
        } catch (e) {
            setMapError(true);
        }
    }, [mapLoaded, lat, lng, name, mapError]);

    // 에러 시 정적 이미지 또는 링크로 대체
    if (mapError) {
        return (
            <a
                href={`https://map.kakao.com/link/to/${encodeURIComponent(name)},${lat},${lng}`}
                target="_blank"
                rel="noopener noreferrer"
                className="group flex h-full w-full items-center justify-center bg-white/80 text-center backdrop-blur transition-all hover:bg-white"
            >
                <div>
                    <Navigation size={32} className="mx-auto text-gray-400 group-hover:text-primary transition-colors mb-3" />
                    <p className="text-gray-700 font-semibold">{name}</p>
                    <p className="text-sm text-gray-400 mt-1">길찾기 열기</p>
                </div>
            </a>
        );
    }

    return (
        <div
            ref={mapRef}
            className="h-full w-full"
        />
    );
}

export default KakaoMap;
