import React, { ReactElement, ReactNode } from 'react'
import { MissingScopeAction, ScopedBlockProps } from './models'
import { useZocksAuth } from '../../store'

export const ScopedBlock: React.FC<ScopedBlockProps> = ({
  scope,
  authActions,
  superScope,
  resource = '**',
  missingScopeAction,
  children,
}) => {
  const zocksAuth = useZocksAuth()
  const { hasScope } = authActions ?? zocksAuth
  const userHasScope = hasScope(resource, scope, superScope)

  if (missingScopeAction === MissingScopeAction.HIDE && !userHasScope) {
    return <></>
  }

  const disabled = missingScopeAction === MissingScopeAction.DISABLE && !userHasScope
  const applyPropsToChildren = (children: ReactNode, newProps = {}): ReactNode => {
    if (!children) {
      return
    }

    return React.Children.map(children, (child) => {
      if (!child || !(child as ReactElement).props) return child // is text node, without a tag
      const recursiveGrandchildren = applyPropsToChildren((child as ReactElement).props.children, newProps)
      const childNewProps = { children: recursiveGrandchildren, ...newProps }
      return React.cloneElement(child as ReactElement, childNewProps)
    })
  }

  return <>{disabled ? applyPropsToChildren(children, { disabled }) : children}</>
}
