import { Map, Placemark, YMaps } from '@pbe/react-yandex-maps';
import React, { Dispatch, SetStateAction } from 'react';

import { Point } from '../model';

type YandexMapProps = {
  points: Point[];
  selectedStation: number | null;
  setSelectedStation: Dispatch<SetStateAction<number | null>>;
};

const mapCenter = [55.751574, 37.573856];

export const YandexMap = ({
  points,
  selectedStation,
  setSelectedStation,
}: YandexMapProps) => {
  return (
    <YMaps
      query={{
        apikey: process.env.NEXT_PUBLIC_YANDEX_MAP_API_KEY,
        lang: 'ru_RU',
        // load: 'geoObject.addon.balloon',
      }}
    >
      <Map
        defaultState={{
          center: points[0]?.coordinates || mapCenter,
          zoom: 11,
          behaviors: ['drag', 'multiTouch', 'dblClickZoom', 'scrollZoom'],
        }}
        options={{
          copyrightUaVisible: false,
          copyrightProvidersVisible: false,
          copyrightLogoVisible: false,
          suppressMapOpenBlock: true,
          suppressObsoleteBrowserNotifier: true,
        }}
        className='h-full max-h-[500px] w-full overflow-hidden rounded-md shadow-lg'
      >
        {points.map((point) => (
          <Placemark
            key={point.id}
            geometry={point.coordinates}
            options={{
              iconLayout: 'default#image',
              iconImageHref:
                !selectedStation || selectedStation === point.id
                  ? '/map/oriyo-marker.png'
                  : '/map/oriyo-inactive-marker.png',
              iconImageSize: selectedStation === point.id ? [70, 70] : [64, 64],
              iconImageOffset: [-24, -36],
            }}
            onClick={() =>
              setSelectedStation(() => {
                if (selectedStation !== null && selectedStation === point.id) {
                  return null;
                }

                return point.id;
              })
            }
          />
        ))}
      </Map>
    </YMaps>
  );
};
