import React, { useState, useEffect, useCallback } from 'react';
import { GiftedChat } from 'react-native-gifted-chat';
import firebase from 'firebase';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { fetchUser } from '../../redux/actions/index'

export function RoomScreen({ route }) {
  const { thread } = route.params;
  const [messages, setMessages] = useState([])

  useEffect(() => {
    const unsubscribe = firebase.firestore() 
    .collection('THREADS')
    .doc(thread._id)
    .collection('MESSAGES')
    .onSnapshot(querySanpshot => {
      const messageFirestore = querySanpshot
        .docChanges() //para traer solo lo que haya cambiado
        .filter(({ type }) => type == 'added') //el objeto tiene un prop added, ese es el que queremos
        .map(({ doc }) => {
          const message = doc.data()
          //return { ...message, createdAt: new Date().getTime() }
          return { ...message, createdAt: message.createdAt.toDate() }
        })
        .sort((a, b) => b.createdAt - a.createdAt)
    appendMessages(messageFirestore) //Para meter el mensaje en el estado messages
    })
    return () => unsubscribe()
  }, [])


  const appendMessages = useCallback((messages) => {
    setMessages((previousMessages) => GiftedChat.append(previousMessages, messages))
  }, [messages])

  async function handleSend(messages) {
    const writes = messages.map(m => firebase.firestore() 
    .collection('THREADS')
    .doc(thread._id)
    .collection('MESSAGES').add(m))
    await Promise.all(writes)
  }

  

  return (
    <GiftedChat messages={messages} user={{ _id: firebase.auth().currentUser.uid }} onSend={handleSend} />
  );
}


const mapStateToProps = (store) => ({
  currentUser: store.userState.currentUser,
})
const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
export default connect(mapStateToProps, mapDispatchProps)(RoomScreen);