import React from 'react'
import { StyleProp, View, ViewStyle, StyleSheet } from 'react-native'

type AutoLayoutChild = React.ReactElement<{
  style?: StyleProp<ViewStyle>
}> | null

/**
 * Wrapper that adds a gap between children
 * This tries to match the Figma "Auto Layout" behaviour
 */
export const AutoLayout: React.FC<{
  gap: number
  children: AutoLayoutChild[]
  style?: StyleProp<ViewStyle>
}> = ({ gap, style, children }) => {
  const flexDirection = StyleSheet.flatten(style)?.flexDirection ?? 'column'
  const orientation = {
    row: 'horizontal',
    'row-reverse': 'horizontal',
    column: 'vertical',
    'column-reverse': 'vertical',
  }[flexDirection] as 'horizontal' | 'vertical'
  const marginType = orientation === 'horizontal' ? 'marginEnd' : 'marginBottom'
  return (
    <View style={style}>
      {React.Children.map(children, (child: AutoLayoutChild, i) =>
        child != null
          ? React.cloneElement(child, {
              style: [
                child.props.style,
                {
                  [marginType]: i < children.length - 1 ? gap : 0,
                },
              ],
            })
          : null
      )}
    </View>
  )
}
