import React, { useContext, useRef } from 'react';
import type { PropsWithChildren, RefObject } from 'react';
import { useMapConfigurer } from '../hooks/use-map-configurer.utils';
import { withFastCompare } from '../../../utils';
import type { MapRef } from '../types';

export type MapInternalContextType = {
  isConfigured: boolean;
  mapRef: RefObject<MapRef>;
};

const MapInternalContext = React.createContext<MapInternalContextType>({
  isConfigured: false,
  mapRef: React.createRef(),
});

export const useMapInternalContext = () => useContext(MapInternalContext);

export const MapProvider = withFastCompare(
  (props: PropsWithChildren<{ mapKey: string; geocodeKey: string }>) => {
    const { isConfigured } = useMapConfigurer(props.mapKey, props.geocodeKey);
    const _mapRef = useRef<MapRef>();

    return (
      <MapInternalContext.Provider
        value={{
          isConfigured,
          mapRef: _mapRef as React.RefObject<MapRef>,
        }}
      >
        {props.children}
      </MapInternalContext.Provider>
    );
  }
);
