import React, { ReactElement } from 'react'
import { responsivePositioningOptions } from '@adalo/constants'
import { connect } from 'react-redux'
import { View, StyleSheet } from 'react-native'
import PropTypes from 'prop-types'
import { RunnerObject, Screen } from 'types'
import { getNodeHeight, RootPushTreeState } from 'ducks/pushTreeMap'

const { FIXED_ON_SCROLL } = responsivePositioningOptions

interface Props {
  children: ReactElement[]
  isResponsiveComponent: boolean
  object: RunnerObject
  screenHeight: number
}

const Wrapper = (props: Props): ReactElement => {
  const {
    children,
    isResponsiveComponent,
    object: { layout: objectLayout, responsivity },
    screenHeight,
  } = props

  const layout = { ...objectLayout }

  if (isResponsiveComponent) {
    layout.height = screenHeight

    if (responsivity?.verticalPositioning === FIXED_ON_SCROLL) {
      layout.height = '100%'
    }
  }

  return (
    <View style={[styles.wrapper, layout]} pointerEvents="box-none">
      {children}
    </View>
  )
}

Wrapper.contextTypes = {
  getOffsetTop: PropTypes.func,
}

Wrapper.whyDidYouRender = {
  logOnDifferentValues: true,
  customName: 'Wrapper',
}

const styles = StyleSheet.create({ wrapper: {} })

interface ConnectProps {
  isResponsiveComponent: boolean
  pushId: string
  component: Screen
}

const mapStateToProps = (
  state: RootPushTreeState,
  { component, isResponsiveComponent, pushId }: ConnectProps
): {
  screenHeight: number
} => {
  const screenHeight = isResponsiveComponent
    ? getNodeHeight(state, component.id, pushId)
    : 0

  return { screenHeight }
}

const ConnectedWrapper = connect(mapStateToProps)(Wrapper)

ConnectedWrapper.whyDidYouRender = {
  logOnDifferentValues: true,
  customName: 'ConnectedWrapper',
}

export default ConnectedWrapper
