import React from 'react';
import { Dimensions, StyleSheet, Text, TextStyle, View, ViewStyle, } from 'react-native';
import { DataProvider, LayoutProvider, RecyclerListView } from 'recyclerlistview';
import { Strings } from '../../resources/localization/Strings';
import { IConversation } from '../../store/conversations/types';
import { IStyledProps } from '../common/types';


interface IProps extends IStyledProps<IConversationStyleProps> {
  conversations: IConversation[];
  renderEmptyList?: () => React.ReactElement;
  renderItems: (conversation: IConversation) => React.ReactElement;
  cellWidth?: number;
  cellHeight?: number;
}
interface IConversationStyleProps {
  NoDataMessages?: TextStyle;
  listContainer?: ViewStyle;
  containerStyle?: ViewStyle;
  center?: ViewStyle;
  noDataText?:TextStyle;
}

export const Conversations: React.FunctionComponent<IProps> = (
  props: IProps
) => {
  const width = props.cellWidth ? props.cellWidth : Dimensions.get('window').width;
  const height = props.cellHeight ? props.cellHeight : 80;
  const mergedStyle = { ...defaultStyle, ...props.style }

  const dataProvider = new DataProvider((r1: any, r2: any) => {
    return r1 !== r2;
  }).cloneWithRows(props.conversations);


  const layoutProvider = new LayoutProvider(() => 'CONVERSATION',
    (type: any, dim: { width: number; height: number }) => {
      switch (type) {
        case 'CONVERSATION':
          dim.width = width;
          dim.height = height;
          break;
        default:
          dim.width = width;
          dim.height = 0;
      }
    }
  );

  const renderItems = (type: string | number, conversation: IConversation) => {
    return props.renderItems(conversation);
  };

  const renderEmptyList = () => {
    if (props.renderEmptyList) {
      return props.renderEmptyList();
    }
    else {
      return (
        <View style={mergedStyle.center}>
        <Text style={mergedStyle.noDataText}>{Strings.noDataFound}</Text>
      </View>
      );
    }
  }

  const renderConversationsListContent = () => {
    if (props.conversations.length === 0) {
      return renderEmptyList();
    }
    else {
      return (
        <View style={mergedStyle.listContainer}>
          <RecyclerListView
            layoutProvider={layoutProvider}
            dataProvider={dataProvider}
            rowRenderer={renderItems}
          />
        </View>
      );
    }
  };

  return (
    <View style={mergedStyle.containerStyle}>
      {renderConversationsListContent()}
    </View>
  );
};

const defaultStyle: IConversationStyleProps = StyleSheet.create({
  NoDataMessages: {
    textAlign: 'center',
  },
  containerStyle: {
    flex: 1,
    backgroundColor: '#ffffff',
  },
  listContainer: {
    flex: 1,
    flexDirection: 'row',
    minHeight: 1,
  },
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  noDataText: {
    color: '#757575',
    fontSize: 16,
  },
});