import { useCallback, useEffect } from 'react'
import type { MeasurementToolsControlProps } from './types'
import { useMeasurementTools } from './use-measurement-tools'
import { getTextLayerFormattedDistance } from './utils'

export function MeasurementToolsControl({
  mapId,
  textOptions,
  children,
}: MeasurementToolsControlProps) {
  const {
    modes,
    units,
    distance,
    setDistance,
    clearLayerOnStart,
    modeSelected,
    setModeSelected,
    enabled,
    setEnabled,
    finished,
    setFinished,
    locale,
    setLocale,
    modeInstance,
    setModeInstance,
    positions,
    setPositions,
    unit,
    setUnit,
    clearLayer,
    toggleLayer: _toggleLayer,
  } = useMeasurementTools({ mapId })

  useEffect(() => {
    if (modeSelected && modes[modeSelected]) {
      const ModeClass = modes[modeSelected].mode
      setModeInstance(new ModeClass())
    }
    return () => {
      setPositions([])
    }
  }, [modes, modeSelected, setPositions, setModeInstance, setEnabled])

  const toggleLayer = useCallback(
    (enable: boolean) => {
      if (enable && (clearLayerOnStart || !finished)) {
        clearLayer()
      }
      _toggleLayer(enable)
    },
    [_toggleLayer, clearLayer, clearLayerOnStart, finished],
  )
  return children({
    mapId,
    distance,
    enabled,
    finished,
    locale,
    positions,
    unit,
    clearLayerOnStart: !!clearLayerOnStart,
    modeSelected: modeSelected!,
    modes,
    units,
    value: getTextLayerFormattedDistance({
      meters: distance,
      unit,
      locale,
      options: textOptions,
    }),
    modeInstance: modeInstance!,
    setModeSelected,
    setDistance,
    setFinished,
    setLocale,
    setPositions,
    setUnit,
    setEnabled,
    toggleLayer,
    clearLayer,
  })
}
