import { IconButton } from '@mui/material'
import { SearchOutlined } from '@mui/icons-material'
import { useCallback, useEffect } from 'react'
import type { SearcherToggleProps, SearcherState } from './types'
import { actionButtonStyles } from '../shared/styles'
import { Tooltip } from '../../../components'
import { widgetStoreActions } from '../../stores/widget-store'
import { useWidgetSelector } from '../../stores/use-widget-selector'

/**
 * Widget action button to toggle search functionality.
 *
 * Stores the enabled state in the widget store using the provided id.
 * When search is active, the button shows an active state with a light background.
 * Use in conjunction with the Searcher component to display the search input.
 *
 * @example
 * ```tsx
 * <SearcherToggle id="my-widget" />
 * <Searcher
 *   id="my-widget"
 *   data={widgetData}
 * />
 * ```
 */
export function SearcherToggle({
  id,
  defaultEnabled = false,
  labels,
  Icon,
  IconButtonProps,
}: SearcherToggleProps) {
  const { storeIsEnabled } = useWidgetSelector(id, (w) => ({
    storeIsEnabled: (w as SearcherState | undefined)?.isSearchEnabled,
  }))

  const isEnabled = storeIsEnabled ?? defaultEnabled

  // Initialize store with default value on mount
  useEffect(() => {
    const currentValue =
      widgetStoreActions.getWidget<SearcherState>(id)?.isSearchEnabled
    if (currentValue === undefined) {
      widgetStoreActions.setWidget(id, { isSearchEnabled: defaultEnabled })
    }
  }, [defaultEnabled, id])

  const handleToggle = useCallback(() => {
    widgetStoreActions.setWidget(id, { isSearchEnabled: !isEnabled })
  }, [id, isEnabled])

  const tooltipLabel = isEnabled
    ? (labels?.disable ?? 'Disable search')
    : (labels?.enable ?? 'Enable search')

  const ariaLabel = labels?.ariaLabel ?? tooltipLabel

  return (
    <Tooltip title={tooltipLabel}>
      <IconButton
        size='small'
        aria-label={ariaLabel}
        onClick={handleToggle}
        sx={actionButtonStyles.trigger}
        data-active={isEnabled}
        {...IconButtonProps}
      >
        {Icon ?? <SearchOutlined fontSize='small' />}
      </IconButton>
    </Tooltip>
  )
}
