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,
  }),
});


let x = "x";
console.log(x);


export function Home_page({navigation}) {

  const [threads, setThreads] = useState([]);  
  const [loading, setLoading] = useState(true);
  const [appointments, setAppointments] = useState([]); 

  const[interpreter, setState] = useState();
  const [Iuser, setIUser] = useState({})
  const [Uuser, setUser] = 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 => {
      if (response.notification.request.content.body == 'Le solicitan una cita'){
        console.log("response appointments ", appointments[0])
        navigation.navigate('Confirm',{tag: appointments[0]})
      } 
    });

    const user_email = firebase.auth().currentUser.email;

  const Iuser_data = firebase.firestore()
  .collection('Interpreters')
  .where("email", "==", user_email)
  .onSnapshot(snapShot => {
    const user = snapShot.docs.map(docSnap => {
      return{
        _id:docSnap.id,
        email:'',
        username:'',
        ...docSnap.data()
      };
    });
      setIUser(user)

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

  const user_data = firebase.firestore()
  .collection('Users')
  .where("email", "==", user_email)
  .onSnapshot(snapShot => {
    const user = snapShot.docs.map(docSnap => {
      return{
        _id:docSnap.id,
        email:'',
        username:'',
        ...docSnap.data()
      };
    });
      setUser(user)

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


    const cita = firebase.firestore().collection('APPOINTMENTS').where("participantes", "array-contains", firebase.auth().currentUser.uid).onSnapshot(snapShot => {
      const appointments = snapShot.docs.map(docSnap => {
        return{
          _id:docSnap.id,
          User:'',
          Interpreter:'',
          new:'',
          Day:'',
          Month:'',
          Time:'',
          i_token:'',
          u_token:'',
          Pin: {},
          ...docSnap.data()
        };
      });
      setAppointments(appointments);
      //console.log("appointment", appointments);
    });

      
    return () => {
      Notifications.removeNotificationSubscription(notificationListener.current);
      Notifications.removeNotificationSubscription(responseListener.current);
      cita();
      Iuser_data();
      user_data();
    }
  }, []);
  
  if (loading) {
    return <Loading />;
  }
   
  
  const dimensions = Dimensions.get('window');
  const screenWidth = dimensions.width;

  
  function check_user_type_INT(){ 

    firebase.firestore()
    .collection("Interpreters")
    .doc(firebase.auth().currentUser.uid)
    .get()
    .then((snapshot) => {
      if(snapshot.exists){
        setState(true);
      }
      else{
        setState(false);
      }
    })

    if(loading){
      setLoading(false);
    }

  }

  function citaId(citaID) {
    firebase.firestore()
      .collection('APPOINTMENTS')
      .doc(citaID)
      .update({
        citaID: citaID,
      })
  }
  

  check_user_type_INT();
  //console.log("interpreter", interpreter);

  
  if(interpreter == false){
    const user_name = Uuser[0].username;
    return (
      <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
      <FlatList style={{
           flex: 1,
           width: screenWidth,
       }}
        data={appointments}
        keyExtractor = {item => item._id}
        ItemSeparatorComponent={() => <Divider />}
        renderItem = {({item}) => (
        <TouchableOpacity
        onPress={async () => {
          //console.log("item._id, home, client", item.Pin)
          navigation.navigate('Cita',{tag: item, Pin: item})
        }}
        >
          <List.Item
            title='Interprete: '
            description={item.Interpreter}
            titleNumberOfLines={1}
            titleStyle={styles.listTitle}
            descriptionStyle={styles.listDescription}
            descriptionNumberOfLines={1}
          />
           <List.Item
            title='Mes:'
            description={item.Month}
            titleNumberOfLines={1}
            titleStyle={styles.listTitle}
            descriptionStyle={styles.listDescription}
            descriptionNumberOfLines={1}
          />
          <List.Item
            title='Día:'
            description={item.Day}
            titleNumberOfLines={1}
            titleStyle={styles.listTitle}
            descriptionStyle={styles.listDescription}
            descriptionNumberOfLines={1}
          />
          <List.Item
            title='Hora:'
            description={item.Time}
            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 }) => {
            if(item.new == 'true'){
            return (
              <Button
              title ='Pedir Cita'
              onPress={ async () => {
                await sendPushNotification(item.i_token);
                citaId(item._id);
                }
              }
            /> 
            )
          }}}
            />
        <Button
          title ='Hacer Busqueda'
          onPress= {() => navigation.navigate('Search', {U_Token: expoPushToken, Username: user_name})}
        />
        <Button
          title ='Logout'
          onPress= {() => firebase.auth().signOut()}
        />
          </ImageBackground>
      );
    }
    else{
      //En caso de que se necesite el username del interprete que esta logged in.
      //const user_name = Iuser[0].username;
      return (
        <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
        <FlatList style={{
             flex: 1,
             width: screenWidth,
         }}
          data={appointments}
          keyExtractor = {item => item._id}
          ItemSeparatorComponent={() => <Divider />}
          renderItem = {({item}) => (
          <TouchableOpacity
          onPress={async () => {
            //console.log("item._id, home, interpreter", item)
            navigation.navigate('Cita',{tag: item, Pin: item})
          }}
          >
          <List.Item
            title='Usuario:'
            description={item.User}
            titleNumberOfLines={1}
            titleStyle={styles.listTitle}
            descriptionStyle={styles.listDescription}
            descriptionNumberOfLines={1}
          />
          <List.Item
            title='Mes:'
            description={item.Month}
            titleNumberOfLines={1}
            titleStyle={styles.listTitle}
            descriptionStyle={styles.listDescription}
            descriptionNumberOfLines={1}
          />
          <List.Item
            title='Día:'
            description={item.Day}
            titleNumberOfLines={1}
            titleStyle={styles.listTitle}
            descriptionStyle={styles.listDescription}
            descriptionNumberOfLines={1}
          />
          <List.Item
            title='Hora:'
            description={item.Time}
            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 }) => {
            if(item.new == 'true'){
            return (
              <Button
              title ='Pedir Cita'
              onPress={ async () => {
                await sendPushNotification(item.i_token);
                citaId(item._id);
                x = item._id;
                console.log(x);
                console.log("en pedir cita, appointments", appointments[0])
                }
              }
            /> 
            )
          }}}
            />


          <Button
          title ='Availability'
          onPress= {() => navigation.navigate('Availability')}
        />
          <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: 'Freehand',
    body: 'Le solicitan una cita',
    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:', 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('Interpreters').doc(firebase.auth().currentUser.uid).update({'push_token': token})
  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);

