import React, { useState, useEffect, useRef } from 'react';

interface DirectionsProps {
    disableTitle?: boolean;
}

const tabs = [
    { id: 'busan', label: '부산 본사' },
    { id: 'gimhae', label: '김해 공장' },
    { id: 'seoul', label: '서울 경기지사' },
];


const tabContent: Record<string, { lat: number; lng: number; address: string; phone: string }> = {
    busan: {
        lat: 35.170833,
        lng: 129.130833,
        address: '부산 해운대구 센텀중앙로 78, 1308호(센텀그린타워)',
        phone: '051-808-8556',
    },
    gimhae: {
        lat: 35.207,
        lng: 128.848,
        address: '경남 김해시 주촌면 골든루트로 80-16',
        phone: '055-123-4567',
    },
    seoul: {
        lat: 37.501274,
        lng: 127.039585,
        address: '서울 강남구 테헤란로 123, 5층',
        phone: '02-987-6543',
    },
};

const Directions: React.FC<DirectionsProps> = ({ disableTitle }) => {
    const [activeTab, setActiveTab] = useState('busan');
    const mapRef = useRef<HTMLDivElement>(null);
    const mapInstanceRef = useRef<naver.maps.Map>(null);
    const markerRef = useRef<naver.maps.Marker>(null);

    useEffect(() => {
        const { naver } = window;
        if (!naver || !mapRef.current) return;

        const location = tabContent[activeTab];
        const position = new naver.maps.LatLng(location.lat, location.lng);

        if (!mapInstanceRef.current) {
            mapInstanceRef.current = new naver.maps.Map(mapRef.current, {
                center: position,
                zoom: 16,
            });
        } else {
            mapInstanceRef.current.setCenter(position);
        }

        // ✅ 기존 마커 제거 후 새로운 마커 설정
        if (markerRef.current) {
            markerRef.current.setMap(null);
        }

        markerRef.current = new naver.maps.Marker({
            position,
            map: mapInstanceRef.current,
        });
    }, [activeTab]);

    return (
        <div className="px-[2vw] pb-[4vw] space-y-[5vw]">
            <div className="max-w-7xl mx-auto">
                {!disableTitle && (
                    <div className="space-y-2">
                        <div className="text-4xl text-blue-900 font-bold font-['Inter']">찾아오시는 길</div>
                    </div>
                )}

                <div className="mx-30 h-40 flex text-center items-center justify-around">
                    {tabs.map((tab, idx) => (
                        <div
                            key={tab.id}
                            className={`w-full py-6 cursor-pointer text-2xl font-semibold font-['Inter'] ${
                                idx !== 0 ? 'border-l' : ''
                            } ${idx !== tabs.length - 1 ? 'border-r' : ''} ${
                                activeTab === tab.id ? 'text-black' : 'text-black/25'
                            }`}
                            style={{ borderColor: '#E0E1E2' }}
                            onClick={() => setActiveTab(tab.id)}
                        >
                            {tab.label}
                        </div>
                    ))}
                </div>
                
                <div className="mx-30">
                    <div style={{ height: '500px' }}>
                        <div id="map" ref={mapRef} style={{ width: '100%', height: '100%' }} />
                    </div>

                    <div className="flex flex-wrap py-6">
                        <div className="w-1/2 px-4">
                            <div className="text-black text-2xl font-semibold font-['Inter'] mb-2">주소</div>
                            <div className="text-black text-xl font-normal font-['Inter']">
                                {tabContent[activeTab].address}
                            </div>
                        </div>
                        <div className="w-1/2 px-4">
                            <div className="text-black text-2xl font-semibold font-['Inter'] mb-2">전화</div>
                            <div className="text-black text-xl font-normal font-['Inter']">
                                {tabContent[activeTab].phone}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Directions;
