import React, {useState, useEffect, useRef} from 'react';
import Tabs, {TabItem} from '@/components/common/Tabs';

const tabItems: TabItem[] = [
  {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<{ disableTitle?: boolean }> = ({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>
        )}
        <Tabs
          items={tabItems}
          activeTab={activeTab}
          onTabChange={setActiveTab}
        >
          <div className="mx-15">
            <div style={{height: '500px'}}>
              <div 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>
        </Tabs>
      </div>
    </div>
  );
};

export default Directions;
