import { useMap } from '@vis.gl/react-google-maps'
import { useEffect, useImperativeHandle, useMemo } from 'react'

import {
  GoogleMapsOverlay,
  type GoogleMapsOverlayProps,
} from '@deck.gl/google-maps'
import type { DeckGLComponentProps } from '../types'

/**
 * A very simple implementation of a component that renders a list of deck.gl layers
 * via the GoogleMapsOverlay into the <Map> component containing it.
 */
export const DeckGlOverlay = (
  props: GoogleMapsOverlayProps & {
    instanceRef?: DeckGLComponentProps['instanceRef']
  },
) => {
  // the GoogleMapsOverlay can persist throughout the lifetime of the DeckGlOverlay
  const deck = useMemo(
    () =>
      new GoogleMapsOverlay({
        interleaved: true,
      }),
    [],
  )

  // add the overlay to the map once the map is available
  const map = useMap()

  useImperativeHandle(
    props.instanceRef,
    () => {
      return deck
    },
    [deck],
  )

  useEffect(() => {
    deck.setMap(map)

    return () => {
      deck.finalize()
    }
  }, [deck, map])

  // whenever the rendered data changes, the layers will be updated
  useEffect(() => {
    deck.setProps(props)
  }, [deck, props])

  // no dom rendered by this component
  return null
}
