import {
  Dialog,
  DialogContent,
  DialogTitle,
  IconButton,
  Typography,
} from '@mui/material'
import { widgetStoreActions } from '../../stores/widget-store'
import { useWidgetSelector } from '../../stores/use-widget-selector'
import { Close, FullscreenOutlined } from '@mui/icons-material'
import type {
  FullScreenConfig,
  FullScreenProps,
  FullScreenState,
} from './types'
import { styles } from './styles'

const EMPTY_DIALOG_CONTENT_PROPS: NonNullable<
  FullScreenProps['DialogContentProps']
> = {}

/**
 * Displays widget content in a fullscreen modal dialog.
 *
 * Manages fullscreen state via the widget store and renders a MUI Dialog
 * with the widget title and a close button.
 *
 * @example
 * ```tsx
 * <FullScreen id="my-widget" labels={{ ariaLabel: 'Expand chart' }}>
 *   <ChartContent id="my-widget" />
 * </FullScreen>
 * ```
 */
export function FullScreen({
  id,
  labels,
  children,
  Icon,
  IconButtonProps,
  DialogContentProps: {
    sx,
    ...DialogContentProps
  } = EMPTY_DIALOG_CONTENT_PROPS,
  DialogProps,
}: FullScreenProps) {
  const { isFullScreen, title } = useWidgetSelector(id, (w) => ({
    isFullScreen: (w as FullScreenState | undefined)?.isFullScreen,
    title: (w as FullScreenState | undefined)?.title,
  }))
  const updateFullScreenConfig = (updates: Partial<FullScreenConfig>) => {
    widgetStoreActions.setWidget<FullScreenState>(id, {
      isFullScreen: updates.isFullScreen,
    })
  }

  return (
    <>
      <IconButton
        {...IconButtonProps}
        onClick={() => updateFullScreenConfig({ isFullScreen: true })}
      >
        {Icon ?? <FullscreenOutlined />}
      </IconButton>
      <Dialog
        maxWidth={false}
        open={!!isFullScreen}
        keepMounted
        aria-labelledby={labels?.ariaLabel ?? `fullscreen-dialog-title-${id}`}
        {...DialogProps}
        onClose={() => updateFullScreenConfig({ isFullScreen: false })}
      >
        <DialogTitle
          id={`fullscreen-dialog-title-${id}`}
          sx={styles.title.container}
        >
          <Typography variant='subtitle1' component='span'>
            {title}
          </Typography>
          <IconButton
            onClick={() => updateFullScreenConfig({ isFullScreen: false })}
          >
            <Close />
          </IconButton>
        </DialogTitle>
        <DialogContent
          sx={{
            ...styles.content,
            ...sx,
          }}
          {...DialogContentProps}
        >
          {children}
        </DialogContent>
      </Dialog>
    </>
  )
}
