import React from 'react'
import PropTypes from 'prop-types'
import { ActivityIndicator, selectSystemProps } from '@telus-uds/components-base'
import styled from 'styled-components'
import { htmlAttrs } from '../utils'
import { BACKDROP_Z_INDEX, LARGE } from './constants'

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

const Container = styled.div(({ overlay }) => ({
  display: 'inline-flex',
  flexDirection: 'column',
  alignItems: 'center',
  ...(overlay && {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    zIndex: BACKDROP_Z_INDEX
  })
}))

const SpinnerContent = React.forwardRef(
  (
    {
      label,
      labelPosition,
      overlay = false,
      sizeVariant,
      size,
      thickness,
      isStatic,
      showLabel = sizeVariant === LARGE,
      ...rest
    },
    ref
  ) => {
    return (
      <Container overlay={overlay} ref={ref} aria-label={label} role="status">
        <ActivityIndicator
          role="progressbar"
          aria-busy="true"
          aria-valuetext={label}
          label={label}
          labelPosition={labelPosition}
          showLabel={showLabel}
          tokens={{ size, thickness }}
          isStatic={isStatic}
          {...selectProps(rest)}
        />
      </Container>
    )
  }
)

SpinnerContent.displayName = 'SpinnerContent'

SpinnerContent.propTypes = {
  ...selectedSystemPropTypes,
  /**
   * Communicates a message to assistive technology while visible. This same message will appear underneath the spinner when its `size` is `large`.
   */
  label: PropTypes.string.isRequired,
  /**
   * Whether the container has to have an overlay styling.
   */
  overlay: PropTypes.bool,
  /**
   * Size (width and height) of the spinner.
   */
  size: PropTypes.number,
  /**
   * The size of the spinner
   */
  sizeVariant: PropTypes.oneOf(['large', 'small']),
  /**
   * If true, it should render a static spinner
   */
  isStatic: PropTypes.bool
}

export default SpinnerContent
