import { useEffect, useRef, useState } from 'react'

import { Box } from '../box'
import { useStyleConfig, vui } from '../core'
import { cs, mergeRefs } from '../utils'
import { useDialogContext } from './context'
import { DialogBodyProps } from './dialog.types'

/**
 * Shows the main content between the Dialog Header and Footer.
 * It becomes scrollable when content does not fit vertically. Borders are shown automatically.
 * Receives more horizontal padding when Dialog has icon, so align text with title.
 * Receives id linked to aria-describedby on the Dialog for accessibility.
 */
export const DialogBody = vui<'div', DialogBodyProps>((props, ref) => {
  const { className, ...rest } = props
  const { bodyId, icon, status } = useDialogContext() ?? {}
  const styles = useStyleConfig('Dialog', useDialogContext())

  const [isScrolled, setIsScrolled] = useState(false)
  const bodyRef = useRef<HTMLDivElement>(null)

  // Observe size changes of the body to detect if it becomes vertically scrollable
  const observerRef = useRef(
    new ResizeObserver(() => {
      if (bodyRef.current) {
        const { clientHeight, scrollHeight } = bodyRef.current
        setIsScrolled(scrollHeight > clientHeight)
      }
    }),
  )

  useEffect(() => {
    bodyRef.current && observerRef.current?.observe(bodyRef.current)
  }, [])

  // If body can be scrolled vertically, add dividing lines on top and bottom
  const borderProps = isScrolled ? { borderColor: 'grey.30' } : {}

  // Add more body padding when custom or status icon is displayed
  const paddingProps = (icon ?? status) !== undefined ? { px: 8 } : { px: 3 }

  return (
    <Box
      borderBottom="1px solid transparent"
      borderTop="1px solid transparent"
      className={cs('vui-dialogBody', className)}
      column
      id={bodyId}
      overflowY="auto"
      pb={2}
      pt={1.5}
      ref={mergeRefs(ref, bodyRef)}
      {...borderProps}
      {...paddingProps}
      {...styles.body}
      {...rest}
    />
  )
})

DialogBody.displayName = 'DialogBody'

export default DialogBody
