import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { View, StyleSheet, ActivityIndicator } from 'react-native'
import { IReduxState } from 'interfaces'
import { connect, Omit } from 'react-redux'
import { solveBindings } from 'utils/library-binding'
import { actionContextTypes } from 'utils/actions'
import {
  BindingDataType,
  SocialMediaListContext,
  SocialMediaListProps,
} from './types'
import { ListItem } from './listItem'

class SimpleSocialMediaList extends Component<SocialMediaListProps> {
  static contextTypes = {
    ...actionContextTypes,
    getLibraryComponent: PropTypes.func,
    isPreviewer: PropTypes.bool,
    getLayoutGuides: PropTypes.func,
  }

  render() {
    const { items } = this.props

    if (!items || items.length === 0) {
      return <ActivityIndicator />
    }

    return (
      <View style={[styles.wrapper]}>
        {items.map(item => (
          <ListItem key={item.id} {...this.props} {...this.context} {...item} />
        ))}
      </View>
    )
  }
}

const mapStateToProps = (
  state: IReduxState,
  props: SocialMediaListProps & SocialMediaListContext
) => {
  const {
    object,
    getParams,
    getBinding,
    getBindingsList,
    getApp,
    getAssetURL,
    getFileUploadsBaseURL,
    getImageUploadsBaseURL,
  } = props
  const bindingData = solveBindings(getApp(), object, {
    state,
    getParams,
    getBinding,
    getBindingsList,
    getAssetURL,
    getFileUploadsBaseURL,
    getImageUploadsBaseURL,
    getApp,
  }) as BindingDataType

  const { componentProps } = bindingData || {
    componentProps: { items: [], background: {} },
  }

  const items = componentProps?.items || []
  const background = componentProps?.background || {
    color: '#fff',
    border: true,
    borderColor: '#999',
    borderWidth: 1,
    borderRadius: 16,
    padding: 6,
  }

  const getDatasources = () => {
    const app = getApp()
    const datasources = app?.datasources

    return datasources
  }

  return {
    items,
    background,
    getDatasources,
  }
}

const ConnectedSocialMediaList = connect(mapStateToProps)(SimpleSocialMediaList)

const WrappedSocialMediaList = (
  props: React.JSX.IntrinsicAttributes &
    Omit<
      React.ClassAttributes<SimpleSocialMediaList> & SocialMediaListProps,
      'items' | 'background'
    > &
    SocialMediaListProps,
  context: SocialMediaListContext
) => <ConnectedSocialMediaList {...props} {...context} />

WrappedSocialMediaList.contextTypes = {
  getApp: PropTypes.func,
  getBinding: PropTypes.func,
  getBindingsList: PropTypes.func,
  getParams: PropTypes.func,
  getFileUploadsBaseURL: PropTypes.func,
  getImageUploadsBaseURL: PropTypes.func,
  getAssetURL: PropTypes.func,
}

export default WrappedSocialMediaList

const styles = StyleSheet.create({
  wrapper: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
})
