import { type ComponentType } from 'react'
import { IconButton, type SvgIconProps } from '@mui/material'
import { Close as CloseIcon } from '@mui/icons-material'
import { Tooltip } from '../../../components'
import { getWidgetStore, useWidgetId } from '../../stores'
import { DEFAULT_SHOW_ALL_LABELS, type ShowAllLabels } from './labels'
import { styles } from './style'

/**
 * The `show-all` flag is a pure UI signal (no data/config transform): the
 * Category overflow row writes it `true` via {@link setShowAll}, the
 * composer reads it with `useTransformEnabled(id, SHOW_ALL_ID)` to drop the
 * row cap, and this button writes it back `false` to collapse. Stored under
 * `transformStates` so `useTransformEnabled` can observe it like any other
 * action flag — but it never registers a pipeline transform, so toggling it
 * never re-runs the data pipeline.
 */
export const SHOW_ALL_ID = 'show-all'

export interface ShowAllToggleProps {
  labels?: Partial<ShowAllLabels>
  icon?: ComponentType<SvgIconProps>
  iconProps?: SvgIconProps
}

/**
 * Collapse (✕) affordance shown while a widget is expanded into its
 * "show all" state. Clicking it clears the `show-all` flag, returning the
 * widget to its capped view. Mount it conditionally (only while the flag is
 * set) so it doesn't occupy a `Widget.Toolbox` visibility-budget slot when
 * the widget is collapsed.
 */
export function ShowAllToggle({
  labels,
  icon: Icon = CloseIcon,
  iconProps,
}: ShowAllToggleProps) {
  const id = useWidgetId()
  const _labels = { ...DEFAULT_SHOW_ALL_LABELS, ...labels }

  return (
    <Tooltip title={_labels.toggle}>
      <IconButton
        size='small'
        aria-label={_labels.toggle}
        aria-pressed
        onClick={() => setShowAll(id, false)}
        sx={styles.toggle}
      >
        <Icon fontSize='small' {...iconProps} />
      </IconButton>
    </Tooltip>
  )
}

/**
 * Imperatively writes the `show-all` flag into the widget store. Mirrors
 * {@link setSearcherText} — used by the Category overflow row (to expand)
 * and the {@link ShowAllToggle} button (to collapse) without routing through
 * a re-rendered subscription.
 */
export function setShowAll(widgetId: string, value: boolean): void {
  getWidgetStore(widgetId).setState((s) => ({
    transformStates: {
      ...s.transformStates,
      [SHOW_ALL_ID]: {
        ...s.transformStates[SHOW_ALL_ID],
        enabled: value,
      },
    },
  }))
}
