import type { MouseEvent } from 'react'
import { CircularProgress, MenuItem } from '@mui/material'
import { useLegendId, useLegendStore } from '../../stores'
import { useLegendConfig } from '../../provider'
import { useLegendMenu, useLegendRow } from '../contexts'
import { runAsyncMenuAction } from '../run-async-menu-action'

export interface LegendZoomToProps {
  /** Fit viewport to the layer; may return a Promise for async menu feedback. */
  onZoomTo: (layerId: string) => void | Promise<void>
}

/**
 * Zoom-to-layer menu item for `Legend.RowMenu`. Self-hides when the layer is hidden.
 *
 * @experimental This API is new and may change in a future release.
 */
export function LegendZoomTo({ onZoomTo }: LegendZoomToProps) {
  const id = useLegendId()
  const row = useLegendRow()
  const menu = useLegendMenu()
  const visible = useLegendStore(id, (s) =>
    row ? (s.layers[row.layerId]?.visible ?? false) : false,
  )
  const { labels } = useLegendConfig()

  if (!row || !visible) return null

  const busy = menu?.busy ?? false

  const handleClick = (e: MouseEvent) => {
    e.stopPropagation()
    if (!menu) return
    void runAsyncMenuAction(menu, () => onZoomTo(row.layerId))
  }

  return (
    <MenuItem disabled={busy} onClick={handleClick}>
      {busy && <CircularProgress size={16} sx={{ mr: 1 }} />}
      {busy ? labels.loading : labels.zoomTo}
    </MenuItem>
  )
}
