import React from 'react'
import PropTypes from 'prop-types'
import { Typography } from '@telus-uds/components-base'
import Image from '../Image'
import SkeletonTypography from './SkeletonTypography'
import SkeletonImage from './SkeletonImage'

const SkeletonProvider = ({ children, show }) => {
  if (!show) {
    return children
  }

  const mapChild = (child) => {
    if (!child) {
      return null
    }

    let childElement = child

    if (childElement.props && 'children' in childElement.props) {
      const { children: elementChildren } = childElement.props
      const mappedChildren = Array.isArray(elementChildren)
        ? elementChildren.map(mapChild)
        : mapChild(elementChildren)
      childElement = React.cloneElement(childElement, {
        children: mappedChildren
      })
    }

    if (childElement.type === Typography) {
      return (
        <SkeletonTypography {...childElement.props.skeleton} show={show}>
          {childElement}
        </SkeletonTypography>
      )
    }

    if (childElement.type === Image) {
      return (
        <SkeletonImage
          {...childElement.props.skeleton}
          imgHeight={childElement.props.height}
          rounded={childElement.props.rounded}
          show={show}
        >
          {childElement}
        </SkeletonImage>
      )
    }

    return childElement
  }

  return <>{React.Children.map(children, mapChild)}</>
}

SkeletonProvider.propTypes = {
  show: PropTypes.bool.isRequired,
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired
}

export default SkeletonProvider
