import { MenuItem } from '@mui/material'
import { getLegendStore, selectLayersByGroup, useLegendId } from '../../stores'
import { useLegendConfig } from '../../provider'
import { useLegendGroupId, useLegendRow } from '../contexts'

/**
 * Show only this layer (and hide siblings in the same bucket).
 *
 * @experimental This API is new and may change in a future release.
 */
export function LegendShowOnlyLayer() {
  const id = useLegendId()
  const row = useLegendRow()
  const { labels } = useLegendConfig()

  if (!row) return null

  const showOnly = () => {
    const state = getLegendStore(id).getState()
    const target = state.layers[row.layerId]
    // No-op if the layer vanished (e.g. a provider resync while the menu was
    // open) — otherwise `groupId: undefined` would act on the ungrouped bucket.
    if (!target) return
    for (const layer of selectLayersByGroup(state, target.groupId)) {
      state.setVisibility(layer.id, layer.id === row.layerId)
    }
  }

  return <MenuItem onClick={showOnly}>{labels.showOnlyLayer}</MenuItem>
}

/**
 * Show all layers in the enclosing group, or all ungrouped layers at row scope.
 *
 * @experimental This API is new and may change in a future release.
 */
export function LegendShowAllLayers() {
  const id = useLegendId()
  const groupId = useLegendGroupId()
  const row = useLegendRow()
  const { labels } = useLegendConfig()

  if (groupId === null && !row) return null

  const showAll = () => {
    const state = getLegendStore(id).getState()
    if (groupId !== null) {
      state.setGroupVisibility(groupId, true)
    } else {
      for (const layer of selectLayersByGroup(state, undefined)) {
        state.setVisibility(layer.id, true)
      }
    }
  }

  return <MenuItem onClick={showAll}>{labels.showAllLayers}</MenuItem>
}
