import React from 'react'

import { Box } from '../box'
import { useStyleConfig, vui } from '../core'
import { cs, isJsx, isReactText, isString } from '../utils'
import { useDialogContext } from './context'
import { DialogHeaderProps } from './dialog.types'
import DialogCloseButton from './dialogCloseButton'
import DialogIcon from './dialogIcon'
import DialogTitle from './dialogTitle'

/** Shows title, status icon and close button above the Dialog Body. */
export const DialogHeader = vui<'div', DialogHeaderProps>((props, ref) => {
  const { children, className, closeButton, icon: iconProp, title: titleProp, ...rest } = props
  const { onClose, status } = useDialogContext() ?? {}
  const styles = useStyleConfig('Dialog', useDialogContext())

  const icon = isString(iconProp) ? { name: iconProp } : iconProp
  const showCloseButton = Boolean(closeButton !== undefined ? closeButton : onClose)
  const showIcon = Boolean(icon || status)
  const title = isReactText(titleProp) ? { text: titleProp } : titleProp

  return (
    <Box
      className={cs('vui-dialogHeader', className)}
      icon={icon}
      pb={1.5}
      pl={3}
      position="relative"
      pr={8}
      pt={3}
      ref={ref}
      {...styles.header}
      {...rest}
    >
      {children ?? (
        <>
          {isJsx(icon) ? icon : showIcon && <DialogIcon {...icon} />}

          {isJsx(title) ? title : title && <DialogTitle {...(title as any)} />}

          {isJsx(closeButton) ? closeButton : showCloseButton && <DialogCloseButton />}
        </>
      )}
    </Box>
  )
})

DialogHeader.displayName = 'DialogHeader'
export default DialogHeader
