import * as React from 'react'
import { Box, PolymorphicComponentProps } from 'react-polymorphic-box'

import './BoundedView.css'

const defaultElement = 'div'

export type BoundedViewPropsBase = {
  /** Maximum width of the content. Any valid CSS measurement can be used. */
  maxWidth?: string | number
  /** Props applied to the inner `<div>`. */
  innerProps?: React.DetailedHTMLProps<
    React.HTMLAttributes<HTMLDivElement>,
    HTMLDivElement
  >
  /** Children contained within the inner constrained `<div>` */
  children?: React.ReactNode
}

export type BoundedViewProps<
  E extends React.ElementType
> = PolymorphicComponentProps<E, BoundedViewPropsBase>

/**
 * `<View>` with a horizontally centered nested `<div>` with an optional
 * maximum width. Gutter width should be added directly to `<BoundedView>` as
 * padding.
 *
 * @example
 * With no inner maximum width:
 * <BoundedView>Content</BoundedView>
 *
 * @example
 * With inner maximum width of `48rem`:
 * <BoundedView maxWidth="48rem">Content</BoundedView>
 */
export const BoundedView: <E extends React.ElementType = typeof defaultElement>(
  props: BoundedViewProps<E>,
) => React.ReactElement | null = React.forwardRef(
  <E extends React.ElementType = typeof defaultElement>(
    { ref, maxWidth, innerProps, children, ...props }: BoundedViewProps<E>,
    innerRef: typeof ref,
  ) => (
    <Box ref={innerRef} as={defaultElement} {...props}>
      <div
        data-siamese-bounded-view-inner=""
        style={{ maxWidth }}
        {...innerProps}
      >
        {children}
      </div>
    </Box>
  ),
)

// @ts-expect-error: Component type does not currently include displayName
BoundedView.displayName = 'BoundedView'
