import React, {useState, useEffect, useRef} from 'react'
import { Button, Text, View, StyleSheet, Dimensions} from 'react-native'
import {FlatList, ListViewBase } from 'react-native'
import {TouchableOpacity} from 'react-native-gesture-handler'
import {List, Divider} from 'react-native-paper'
import Loading from './Loading'
import firebase from 'firebase';
import { styles } from "../../config/styles";
import { TextInput, TouchableWithoutFeedback, Keyboard, ImageBackground} from "react-native";

import { connect } from 'react-redux'
import { bindActionCreators } from 'redux' 
import { fetchUser } from '../../redux/actions/index'

import Constants from 'expo-constants';
import * as Notifications from 'expo-notifications';


Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});


export function Home_page({navigation}) {
  const [threads, setThreads] = useState([]);  
  const [loading, setLoading] = useState(true);
  const [appointments, setAppointments] = useState([]); 
  
  const [roomName, setRoomName] = useState('');



  const [expoPushToken, setExpoPushToken] = useState('');
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();


  useEffect(() => {
    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
      setNotification(notification);
    });

    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
      console.log(response);
    });

    const fire = firebase.firestore()
    .collection('THREADS')
    .where("members", "array-contains", firebase.auth().currentUser.uid)
    .onSnapshot(querySnapshot => {
      const threads = querySnapshot.docs.map(documentSnapshot => {
        return{
          _id:documentSnapshot.id,
          name:'',
          ...documentSnapshot.data()
        };
      });

      setThreads(threads);
      console.log(threads);

      if(loading){
        setLoading(false);
      }
    });

    const cita = firebase.firestore().collection('APPOINTMENTS').where('Day', '==', 8).onSnapshot(snapShot => {
      const appointments = snapShot.docs.map(docSnap => {
        return{
          _id:docSnap.id,
          Day:'',
          Month:'',
          Time:'',
          ...docSnap.data()
        };
      });
      setAppointments(appointments);
      console.log(appointments);
    });
  
      
    //return () => fire();
    return () => {
      Notifications.removeNotificationSubscription(notificationListener.current);
      Notifications.removeNotificationSubscription(responseListener.current);
      fire();
      cita();
    }
  }, []);
  
  if (loading) {
    return <Loading />;
  }

  const sendMessage = (token) => {
    fetch('https://exp.host/--/api/v2/push/send', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Accept-encoding': 'gzip, deflate',
        'Content-type': 'application/json',
      },
      body: JSON.stringify({
        to: token,
        title: 'Ernesto',
        body: 'Freehand message',
        data: { data: 'goes here' },
        _displayInForeground: true,
      }),
    });
  }

  
  function handleButtonPress() {
      firebase.firestore()
        .collection('THREADS')
        .add({
          name: 'PedroFecha',
          members: [
            firebase.auth().currentUser.uid,
            '02yOZHxFcGUX4MNwjeEbAlCShdu1'
          ]
        })
        //.then(() => {
          //navigation.navigate('allChats');
         //});
  }

  const dimensions = Dimensions.get('window');
  const screenWidth = dimensions.width;

  
  return (
      <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
        <FlatList style={{
             flex: 1,
             width: screenWidth,
         }}
          data={threads}
          keyExtractor = {item => item._id}
          ItemSeparatorComponent={() => <Divider />}
          renderItem = {({item}) => (
          <TouchableOpacity
            onPress={() => navigation.navigate('Room', {thread: item})}
          >
            <List.Item
              title={item.name}
              titleNumberOfLines={1}
              titleStyle={styles.listTitle}
              descriptionStyle={styles.listDescription}
              descriptionNumberOfLines={1}
            />
          </TouchableOpacity>
        )}
        />
        <FlatList style={{
             flex: 1,
             width: screenWidth,
         }}
          data={appointments}
          keyExtractor = {item => item._id}
          ItemSeparatorComponent={() => <Divider />}
          renderItem = {({item}) => (
          <TouchableOpacity
          onPress={async () => {
            await sendPushNotification(expoPushToken);
          }}
          >
            <List.Item
              title={item.Month}
              titleNumberOfLines={1}
              titleStyle={styles.listTitle}
              descriptionStyle={styles.listDescription}
              descriptionNumberOfLines={1}
            />
            <List.Item
              title={item.Day}
              titleNumberOfLines={1}
              titleStyle={styles.listTitle}
              descriptionStyle={styles.listDescription}
              descriptionNumberOfLines={1}
            />
            <List.Item
              title={item.Time}
              titleNumberOfLines={1}
              titleStyle={styles.listTitle}
              descriptionStyle={styles.listDescription}
              descriptionNumberOfLines={1}
            />
          </TouchableOpacity>
        )}
        />
      <Text>Your expo push token: {expoPushToken}</Text>
      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
        <Text>Title: {notification && notification.request.content.title} </Text>
        <Text>Body: {notification && notification.request.content.body}</Text>
        <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
      </View>
      <Button
        title="Press to Send Notification"
        onPress={async () => {
          await sendPushNotification(expoPushToken);
        }}
      /> 
      <Button
        title='CrearChat'
        onPress={() => handleButtonPress()}
      />
      <Button
        title ='Hacer Busqueda'
        onPress= {() => navigation.navigate('Search')}
      />
      <Button
        title ='Logout'
        onPress= {() => firebase.auth().signOut()}
      />
        </ImageBackground>
    );
  }
// Can use this function below, OR use Expo's Push Notification Tool-> https://expo.dev/notifications
async function sendPushNotification(expoPushToken) {
  const message = {
    to: expoPushToken,
    sound: 'default',
    title: 'Original Title',
    body: 'And here is the body!',
    data: { someData: 'goes here' },
  };

  await fetch('https://exp.host/--/api/v2/push/send', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Accept-encoding': 'gzip, deflate',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(message),
  });
}

async function registerForPushNotificationsAsync() {
  let token;
  if (Constants.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log(token);
  } else {
    alert('Must use physical device for Push Notifications');
  }

  if (Platform.OS === 'android') {
    Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  firebase.firestore().collection('Users').doc(firebase.auth().currentUser.uid).update({'push_token': token})
  return token;
}

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

export default connect(mapStateToProps, mapDispatchProps)(Home_page);