import { useState } from 'react'
import { ButtonBase, Menu, MenuItem, Typography } from '@mui/material'
import { ArrowDropDown as ArrowDropDownIcon } from '@mui/icons-material'
import { useLegendId, useLegendShallow } from '../../stores'
import { useLegendConfig } from '../../provider'
import { useLegendRow } from '../contexts'
import { styles } from './styles'

/**
 * The layer configuration select — resolves its layer from the enclosing
 * `Legend.Row` context. The closed field shows the **first section's** active
 * option; the menu lists every section under its title (omitted when the
 * layer has a single section) and each section highlights its own active
 * option. Picking an option writes `setSectionValue` and closes the menu.
 * Renders nothing when the layer declares no sections (or outside a row).
 *
 * A native single-value `Select` can't represent one active per section,
 * hence the outlined-trigger + `Menu` composition.
 *
 * @experimental This API is new and may change in a future release.
 */
export function LegendConfigSelect() {
  const id = useLegendId()
  const row = useLegendRow()
  const layerId = row?.layerId
  const sections = useLegendShallow(id, (s) =>
    layerId ? s.layers[layerId]?.sections : undefined,
  )
  const setSectionValue = useLegendShallow(id, (s) => s.setSectionValue)
  const { labels } = useLegendConfig()
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null)
  const open = Boolean(anchorEl)

  if (!layerId || !sections || sections.length === 0) return null

  const display = sections[0]!.active
  const showTitles = sections.length > 1

  return (
    <>
      <ButtonBase
        sx={styles.trigger}
        onClick={(event) => setAnchorEl(event.currentTarget)}
        aria-label={labels.attribute}
        aria-haspopup='listbox'
        aria-expanded={open}
      >
        <Typography variant='body2' sx={styles.value}>
          {display}
        </Typography>
        <ArrowDropDownIcon
          fontSize='small'
          sx={
            open ? { ...styles.chevron, ...styles.chevronOpen } : styles.chevron
          }
        />
      </ButtonBase>

      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={() => setAnchorEl(null)}
        slotProps={{
          paper: { sx: { width: anchorEl?.clientWidth } },
        }}
      >
        {sections.map((section) => [
          showTitles && section.title ? (
            <Typography
              key={`${section.id}-title`}
              variant='overline'
              color='text.secondary'
              component='li'
              sx={styles.sectionTitle}
            >
              {section.title}
            </Typography>
          ) : null,
          ...section.options.map((option) => (
            <MenuItem
              key={`${section.id}-${option}`}
              selected={option === section.active}
              sx={styles.option}
              onClick={() => {
                setSectionValue(layerId, section.id, option)
                setAnchorEl(null)
              }}
            >
              {option}
            </MenuItem>
          )),
        ])}
      </Menu>
    </>
  )
}
