import React, { Component } from 'react';
import {
  FlatList,
  LayoutAnimation,
  StyleSheet,
  View,
} from 'react-native';
import { NavigationActions } from 'react-navigation';
import { connect, Dispatch } from 'react-redux';
import { EmptyView } from '../components/common';
import { ConversationItem } from '../components/common/ConversationItem';
import { Conversation, Message, RootState, UserRole } from '../models';
import { Routes } from '../navigation';
import { RenderErrorView } from './RenderError';

interface StateProps {
  conversations: Array<Conversation & { lastMessage?: Message }>;
  userRole: UserRole;
}

interface DispatchProps {
  onConversationSelected: (conversationId: string) => void;
}

interface State {
  error: boolean;
}

export class ConversationListComponent extends Component<StateProps & DispatchProps, State> {

  state = { error: false };

  getKey = (con: Conversation) => `con${con.id}`;

  renderItem = ({ item }: { item: Conversation }) => {

    return (
      <ConversationItem
        data={item}
        userRole={this.props.userRole}
        onPress={() => this.props.onConversationSelected(item.id)}
      />
    );
  }

  componentDidCatch(error) {
    this.setState({ error: true });
  }

  renderEmpty() {
    const sufix = this.props.userRole === UserRole.EMPLOYEE
      ? 'pracodawcami'
      : 'pracownikami';
    return <EmptyView text={'Tutaj znajdziesz listę konwersacji z ' + sufix} />;
  }

  componentWillUpdate() {
    LayoutAnimation.easeInEaseOut();
  }

  render() {
    if (this.state.error) return <RenderErrorView />;

    const conversations = this.props.conversations.filter((conversation) => !!conversation.lastMessage);
    return conversations.length > 0 && (
      <View style={styles.container}>
        <FlatList
          data={conversations}
          keyExtractor={this.getKey}
          renderItem={this.renderItem}
        />
      </View>
    ) || this.renderEmpty();
  }
}

const mapStateToProps: (state: RootState) => StateProps =
  (state) => {
    return {
      userRole: state.user.role,
      conversations: state.conversations.map((conversation) => {
        const messages = state.chats[conversation.id].messages || [];
        return {
          ...conversation,
          lastMessage: messages.sort((a, b) => b.timestamp - a.timestamp)[0],
        };
      }),
    };
  };

const mapDispatchToProps: (dispatch: Dispatch<RootState>) => DispatchProps =
  (dispatch) => ({
    onConversationSelected: (conversationId) => dispatch(NavigationActions.navigate({
      routeName: Routes.CHATROOM,
      params: { conversationId },
    })),
  });

export const ConversationList = connect(mapStateToProps, mapDispatchToProps)(ConversationListComponent);

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});
