import { type ComponentType } from 'react'
import { IconButton, type SvgIconProps } from '@mui/material'
import { StackedBarChart as StackedBarChartIcon } from '@mui/icons-material'
import { Tooltip } from '../../../components'
import { useSingleTransform, useWidgetId } from '../../stores'
import { addStack } from './transforms'
import { DEFAULT_STACK_TOGGLE_LABELS, type StackToggleLabels } from './labels'
import { styles } from './style'

const STACK_DESCRIPTOR = {
  id: 'stack-toggle',
  type: 'config' as const,
  order: 30,
}

export interface StackToggleProps {
  initialEnabled?: boolean
  labels?: Partial<StackToggleLabels>
  icon?: ComponentType<SvgIconProps>
  iconProps?: SvgIconProps
}

export function StackToggle({
  initialEnabled = false,
  labels,
  icon: Icon = StackedBarChartIcon,
  iconProps,
}: StackToggleProps) {
  const id = useWidgetId()
  const _labels = { ...DEFAULT_STACK_TOGGLE_LABELS, ...labels }
  const { enabled, toggle } = useSingleTransform(
    id,
    STACK_DESCRIPTOR,
    addStack,
    {
      initialEnabled,
    },
  )
  const tooltip = enabled ? _labels.on : _labels.off

  return (
    <Tooltip title={tooltip}>
      <IconButton
        size='small'
        aria-label={tooltip}
        aria-pressed={enabled}
        onClick={toggle}
        sx={{ ...styles.toggle, ...(enabled && styles.toggleActive) }}
      >
        <Icon fontSize='small' {...iconProps} />
      </IconButton>
    </Tooltip>
  )
}
