import type { WrapperProps, WrapperState } from './types'
import { WrapperUI } from './wrapper-ui'
import { widgetStoreActions } from '../stores/widget-store'
import { useLayoutEffect } from 'react'

/**
 * Container component providing a collapsible header with title, action buttons, and options menu for widgets. Syncs collapse, disabled, and title state with the widget store.
 *
 * @example
 * ```tsx
 * <WidgetWrapper
 *   id="my-widget"
 *   title="Sales Overview"
 *   actions={[<Download key="download" id="my-widget" items={downloads} />]}
 * >
 *   {children}
 * </WidgetWrapper>
 * ```
 */
export function WidgetWrapper({
  id,
  title,
  defaultCollapsed,
  disabled,
  sx,
  actions,
  options,
  labels,
  children,
  onChangeCollapsed,
}: WrapperProps) {
  useLayoutEffect(() => {
    widgetStoreActions.setWidget<WrapperState>(id, {
      collapsed: defaultCollapsed,
      disabled,
      title,
    })
  }, [defaultCollapsed, disabled, title, id])

  const handleChangeCollapsed = (
    event: React.SyntheticEvent<Element, Event>,
    expanded: boolean,
  ) => {
    onChangeCollapsed?.(event, expanded)
    widgetStoreActions.setWidget<WrapperState>(id, { collapsed: !expanded })
  }

  return (
    <WrapperUI
      id={id}
      labels={labels}
      actions={actions}
      options={options}
      sx={sx}
      onChangeCollapsed={handleChangeCollapsed}
    >
      {children}
    </WrapperUI>
  )
}
