import React, { useState } from 'react'
import { Text, View,  StyleSheet, FlatList, TouchableOpacity } from 'react-native'
import SelectBox from 'react-native-multi-selectbox'
import { xorBy } from 'lodash'
import firebase from 'firebase'
import { firebaseConfig } from '../../config/firebaseConfig'
  

if (firebase.apps.length === 0) {
  firebase.initializeApp(firebaseConfig)
}

require('firebase/firestore')
// Options data must contain 'item' & 'id' keys

const Tags = [
  {
    item: 'Presencial',
    id: 'PL',
  },
  {
    item: 'Online',
    id: 'ON',
  },
  {
    item: 'Individual',
    id: 'IL',
  },
  {
    item: 'Grupal',
    id: 'GL',
  },
  {
    item: 'Esp',
    id: 'ESP',
  },
  {
    item: 'Ing',
    id: 'ING',
  }

]


const Days = [
  {
    item: 'Lunes',
    id: 'L',
  },
  {
    item: 'Martes',
    id: 'M',
  },
  {
    item: 'Miercoles',
    id: 'W',
  },
  {
    item: 'Jueves',
    id: 'J',
  },
  {
    item: 'Viernes',
    id: 'V',
  },
  {
    item: 'Sabado',
    id: 'S',
  },
  {
    item: 'Domingo',
    id: 'D',
  },
  {
    item: 'Feriados',
    id: 'F',
  }
]



function Search({ navigation }) {

  
  const [users, setUsers] = useState([])
  const [selectedTags, setSelectedTags] = useState([])
  const [selectedDays, setSelectedDays] = useState([])

  
  const fetchUsers = (tags, days) => {
    
    //if the array that have the interpreter tags
    //and the day tags are empty we dont send the query seeing as the user
    //is not searching for anything yet 
    if (tags.length === 0 && days.length === 0) {
      return
    }

    //reset the users usestate to empty
    const users = []
    
    

    const db = firebase.firestore()
    var query = db.collection('Interprete')
    
    for (let i = 0; i < tags.length; i++) {
      //check which tags where called in the search 
      if (tags[i].id === 'PL') {
        console.log('Presencial')
        query = query.where('Modalidad.Presencial', '==', true)
      }
      if (tags[i] == 'OL') {
        query = query.where('Modalidad.Online', '==', true)
      }
      if (tags[i] == 'IL') {
        query = query.where('Cantidad.Individual', '==', true)
      }
      if (tags[i] == 'GL') {
        query = query.where('Cantidad.Grupal', '==', true)
      }
      if (tags[i] == 'ESP') {
        query = query.where('Lenguaje.Esp', '==', true)
      }
      if (tags[i] == 'ING') {
        query = query.where('Lenguaje.Ing', '==', true)
      }
  }
  for(let i = 0; i < days.length; i++) {
    if (days[i].id === 'L') {
      query = query.where('dias.Lunes', '==', true)
    }
    if (days[i].id === 'M') {
      query = query.where('dias.Martes', '==', true)
    }
    if (days[i].id === 'W') {
      query = query.where('dias.Miercoles', '==', true)
    }
    if (days[i].id === 'J') {
      query = query.where('dias.Jueves', '==', true)
    }
    if (days[i].id === 'V') {
      query = query.where('dias.Viernes', '==', true)
    }
    if (days[i].id === 'S') {
      query = query.where('dias.Sabado', '==', true)
    }
    if (days[i].id === 'D') {
      query = query.where('dias.Domingo', '==', true)
    }
    if (days[i].id === 'F') {
      query = query.where('dias.Feriados', '==', true)
    }
  }
    query.get().then(querySnapshot => {
      console.log('Total users: ', querySnapshot.size);
      //traverse the query snapshot
      //add the user to the users array
      querySnapshot.forEach(documentSnapshot => {
        //save the user id and the user data
        const user = {
          id: documentSnapshot.id,
          data: documentSnapshot.data()
        }
        users.push(user)
        setUsers(users)
      });
    });
    console.log('These are the users after the query is executed: ',  users)
    
  }


  return (
    <View style={{ margin: 30 }}>
      <View style={{ width: '100%', alignItems: 'center' }}>
        <Text style={{ fontSize: 30, paddingBottom: 20 }}>Busqueda</Text>
      </View>
      <Text style={{ fontSize: 20, paddingBottom: 10 }}>Filtro de Interpretes</Text>
      <SelectBox
        arrowIconColor='#E4CD05'
        toggleIconColor='#E4CD05'
        searchIconColor='#E4CD05'
        multiOptionContainerStyle = {{
          backgroundColor: '#E4CD05',
          borderColor: '#E4CD05',
          borderWidth: 1,
          borderRadius: 5,
          marginBottom: 10,
          marginTop: 10,
          padding: 10,
        }}
        multiOptionsLabelStyle = {{
          color: '#000000',
          fontSize: 20,
        }}
        label="Select multiple"
        options={Tags}
        selectedValues={selectedTags}
        onMultiSelect={onMultiChange()}
        onTapClose={onMultiChange()}
        isMulti
      />
      <Text style={{ fontSize: 20, paddingBottom: 10 }}>Dias Disponibles</Text>
      <SelectBox
      arrowIconColor='#E4CD05'
      toggleIconColor='#E4CD05'
      searchIconColor='#E4CD05'
      multiOptionContainerStyle = {{
        backgroundColor: '#E4CD05',
        borderColor: '#E4CD05',
        borderWidth: 1,
        borderRadius: 5,
        marginBottom: 10,
        marginTop: 10,
        padding: 10,
      }}
      multiOptionsLabelStyle = {{
        color: '#000000',
        fontSize: 20,
      }}
        label="Select multiple"
        options={Days}
        selectedValues={selectedDays}
        onMultiSelect={(item) => setSelectedDays(xorBy(selectedDays, [item], 'id'))}
        onTapClose={(item) => setSelectedDays(xorBy(selectedDays, [item], 'id'))}
        isMulti
      />

      {/* button that will fetch the users */}
      <button onClick={() => fetchUsers(selectedTags, selectedDays)}>Buscar</button>


      <FlatList
        numColumns={1}
        horizontal={false}
        data={users}
        
        renderItem={({ item, }) => {
          return (
            <View style={{ flexDirection: "row", justifyContent: "space-between" }}>
              <Text>{item.data.name}</Text>
              <button  styles = {styles.button}     onClick={() => { dothing(item.id) }}>Button</button>
            </View>
          )
        }}
        />

    </View>
  );

  function onMultiChange() {
    return (item) => setSelectedTags(xorBy(selectedTags, [item], 'id'))
  }
  
  function dothing(item) {
    console.log('This is the item id: ', item)
    navigation.navigate('Calendar', {Intereprete_id: item})
  } 

}

const styles = StyleSheet.create({
  
  button: {
    alignItems: "center",
    backgroundColor: 'transparent'
  },
});




export default Search