import React from 'react'
import PropTypes from 'prop-types'

import { cssReset } from './cssReset'

import { selectSystemProps } from '../utils/props/selectSystemProps'
import { a11yProps } from '../utils/props/a11yProps'
import { htmlAttrs } from '../utils/htmlAttrs'

const [selectProps, selectedSystemPropTypes] = selectSystemProps([a11yProps, htmlAttrs])

/**
 * On Web, wraps children with a HTML `<fieldset>` and sets its attributes as necessary.
 */
export const FieldsetContainer = React.forwardRef(
  (
    {
      children,
      inactive,
      accessibilityRole,
      name: fieldsetName,
      showBorderStyle = false,
      borderStyle,
      style,
      ...rest
    },
    ref
  ) => {
    // If needs border for error design or reset the component style
    const styleContainer = showBorderStyle && borderStyle ? borderStyle : cssReset
    return (
      <fieldset
        ref={ref}
        disabled={inactive}
        style={{ ...styleContainer, ...style }}
        role={accessibilityRole}
        name={fieldsetName}
        {...selectProps(rest)}
      >
        {children}
      </fieldset>
    )
  }
)
FieldsetContainer.displayName = 'FieldsetContainer'

FieldsetContainer.propTypes = {
  ...selectedSystemPropTypes,
  accessibilityRole: PropTypes.string,
  children: PropTypes.node,
  inactive: PropTypes.bool,
  name: PropTypes.string,
  showBorderStyle: PropTypes.bool,
  borderStyle: PropTypes.object,
  style: PropTypes.object
}
