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

export 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 = React.Children.map(elementChildren, mapChild)
      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
}
