import React, { useState } from 'react'
import { Text, View,  StyleSheet, FlatList, TouchableOpacity, Button, ScrollView } from 'react-native'
import SelectBox from 'react-native-multi-selectbox'
import { xorBy } from 'lodash'
import firebase from 'firebase'
import { firebaseConfig } from '../../config/firebaseConfig'
  
//Flag to indicate an IRL appointment.
var mapflag = false

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 City = [
  {
    item: 'None',
    id: -1,
  },
  {
      item: 'Adjuntas',
      id: 0,
  },
  {
      item: 'Aguada',
      id: 1,
  },
  {
      item: 'Aguadilla',
      id: 2,
  },
  {
      item: 'Aguas Buenas',
      id: 3,
  },
  {
      item: 'Aibonito',
      id: 4,
  },
  {
      item: 'Arecibo',
      id: 5,
  },
  {
      item: 'Arroyo',
      id: 6,
  },
  {
      item: 'Añasco',
      id: 7,
  },
  {
      item: 'Barceloneta',
      id: 8,
  },
  {
      item: 'Barranquitas',
      id: 9,
  },
  {
      item: 'Bayamón',
      id: 10,
  },
  {
      item: 'Cabo Rojo',
      id: 11,
  },
  {
      item: 'Caguas',
      id: 12,
  },
  {
      item: 'Camuy',
      id: 13,
  },
  {
      item: 'Canóvanas',
      id: 14,
  },
  {
      item: 'Carolina',
      id: 15,
  },
  {
      item: 'Cataño',
      id: 16,
  },
  {
      item: 'Cayey',
      id: 17,
  },
  {
      item: 'Ceiba',
      id: 18,
  },
  {
      item: 'Ciales',
      id: 19,
  },
  {
      item: 'Cidra',
      id: 20,
  },
  {
      item: 'Coamo',
      id: 21,
  },
  {
      item: 'Comerío',
      id: 22,
  },
  {
      item: 'Corozal',
      id: 23,
  },
  {
      item: 'Culebra',
      id: 24,
  },
  {
      item: 'Dorado',
      id: 25,
  },
  {
      item: 'Fajardo',
      id: 26,
  },
  {
      item: 'Florida',
      id: 27,
  },
  {
      item: 'Guayama',
      id: 28,
  },
  {
      item: 'Guayanilla',
      id: 29,
  },
  {
      item: 'Guaynabo',
      id: 30,
  },
  {
      item: 'Gurabo',
      id: 31,
  },
  {
      item: 'Guánica',
      id: 32,
  },
  {
      item: 'Hatillo',
      id: 33,
  },
  {
      item: 'Hormigueros',
      id: 34,
  },
  {
      item: 'Humacao',
      id: 35,
  },
  {
      item: 'Isabela',
      id: 36,
  },
  {
      item: 'Jayuya',
      id: 37,
  },
  {
      item: 'Juana Díaz',
      id: 38,
  },
  {
      item: 'Juncos',
      id: 39,
  },
  {
      item: 'Lajas',
      id: 40,
  },
  {
      item: 'Lares',
      id: 41,
  },
  {
      item: 'Las Marías',
      id: 42,
  },
  {
      item: 'Las Piedras',
      id: 43,
  },
  {
      item: 'Loíza',
      id: 44,
  },
  {
      item: 'Luquillo',
      id: 45,
  },
  {
      item: 'Manatí',
      id: 46,
  },
  {
      item: 'Maricao',
      id: 47,
  },
  {
      item: 'Maunabo',
      id: 48,
  },
  {
      item: 'Mayagüez',
      id: 49,
  },
  {
      item: 'Moca',
      id: 50,
  },
  {
      item: 'Morovis',
      id: 51,
  },
  {
      item: 'Naguabo',
      id: 52,
  },
  {
      item: 'Naranjito',
      id: 53,
  },
  {
      item: 'Orocovis',
      id: 54,
  },
  {
      item: 'Patillas',
      id: 55,
  },
  {
      item: 'Peñuelas',
      id: 56,
  },
  {
      item: 'Ponce',
      id: 57,
  },
  {
      item: 'Quebradillas',
      id: 58,
  },
  {
      item: 'Rincón',
      id: 59,
  },
  {
      item: 'Rio Grande',
      id: 60,
  },
  {
      item: 'Sabana Grande',
      id: 61,
  },
  {
      item: 'Salinas',
      id: 62,
  },
  {
      item: 'San Germán',
      id: 63,
  },
  {
      item: 'San Juan',
      id: 64,
  },
  {
      item: 'San Lorenzo',
      id: 65,
  },
  {
      item: 'San Sebastián',
      id: 66,
  },
  {
      item: 'Santa Isabel',
      id: 67,
  },
  {
      item: 'Toa Alta',
      id: 68,
  },
  {
      item: 'Toa Baja',
      id: 69,
  },
  {
      item: 'Trujillo Alto',
      id: 70,
  },
  {
      item: 'Utuado',
      id: 71,
  },
  {
      item: 'Vega Alta',
      id: 72,
  },
  {
      item: 'Vega Baja',
      id: 73,
  },
  {
      item: 'Vieques',
      id: 74,
  },
  {
      item: 'Villalba',
      id: 75,
  },
  {
      item: 'Yabucoa',
      id: 76,
  },
  {
      item: 'Yauco',
      id: 77,
  },
  

]


function Search({route, navigation }) {

  const u_token = route.params.U_Token;
  const username = route.params.Username;
  console.log("U__token: ", u_token)
  
  const [users, setUsers] = useState([])
  const [selectedTags, setSelectedTags] = useState([])
  const [selectedCity, setSelectedCity] = useState([])


  
  const fetchUsers = (tags, city) => {
    
    //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 
    // console.log(tags.length)
    // console.log(city.id)
    if (tags.length === 0 && (typeof city.id ==="undefined" || city.id === -1)) {
      return
    }

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

    const db = firebase.firestore()
    var query = db.collection('Interpreters')
    
    for (let i = 0; i < tags.length; i++) {

      //Reset Flag.
      mapflag = false

      //check which tags where called in the search 
      if (tags[i].id === 'PL') {
        console.log('Presencial')
        query = query.where('face_to_face', '==', true)
        mapflag = true
      }
      if (tags[i].id == 'ON') {
        query = query.where('virtual', '==', true)
      }
      if (tags[i].id == 'IL') {
        query = query.where('personal', '==', true)
      }
      if (tags[i].id == 'GL') {
        query = query.where('group', '==', true)
      }
      if (tags[i].id == 'ESP') {
        query = query.where('spanish', '==', true)
      }
      if (tags[i].id == 'ING') {
        query = query.where('english', '==', true)
      }
  }
  

    
    switch(city.id){
      case 0:
        query = query.where('city', '==', 'Adjuntas')
        break;


      case 1:
        query = query.where('city', '==', 'Aguada')
        break;

      case 2:
        query = query.where('city', '==', 'Aguadilla')
        break;

      case 3:
        query = query.where('city', '==', 'Aguas Buenas')
        break;
      
      case 4:
        query = query.where('city', '==', 'Aibonito')
        break;
      
      case 5:
        query = query.where('city', '==', 'Arecibo')
        break;
      
      case 6:
        query = query.where('city', '==', 'Arroyo')
        break;
      
      case 7:
        query = query.where('city', '==', 'Añasco')
        break;
      
      case 8:
        query = query.where('city', '==', 'Barceloneta')
        break;
      
      case 9:
        query = query.where('city', '==', 'Barranquitas')
        break;
      
      case 10:
        query = query.where('city', '==', 'Bayamón')
        break;
      
      case 11:
        query = query.where('city', '==', 'Cabo Rojo')
        break;
      
      case 12:
        query = query.where('city', '==', 'Caguas')
        break;
      
      case 13:
        query = query.where('city', '==', 'Camuy')
        break;
      
      case 14:
        query = query.where('city', '==', 'Canóvanas')
        break;
      
      case 15:
        query = query.where('city', '==', 'Carolina')
        break;

      case 16:
        query = query.where('city', '==', 'Cataño')
        break;

      case 17:
        query = query.where('city', '==', 'Cayey')
        break;

      case 18:
        query = query.where('city', '==', 'Ceiba')
        break;

      case 19:
        query = query.where('city', '==', 'Ciales')
        break;
      
      case 20:
        query = query.where('city', '==', 'Cidra')
        break;

      case 21:
        query = query.where('city', '==', 'Coamo')
        break;

      case 22:
        query = query.where('city', '==', 'Comerío')
        break;

      case 23:
        query = query.where('city', '==', 'Corozal')
        break;

      case 24:
        query = query.where('city', '==', 'Culebra')
        break;
      
      case 25:
        query = query.where('city', '==', 'Dorado')
        break;

      case 26:
        query = query.where('city', '==', 'Fajardo')
        break;

      case 27:
        query = query.where('city', '==', 'Florida')
        break;

      case 28:
        query = query.where('city', '==', 'Guánica')
        break;
      
      case 29:
        query = query.where('city', '==', 'Guayama')
        break;

      case 30:
        query = query.where('city', '==', 'Guayanilla')
        break;
      
      case 31:
        query = query.where('city', '==', 'Guaynabo')
        break;

      case 32:
        query = query.where('city', '==', 'Gurabo')
        break;

      case 33:
        query = query.where('city', '==', 'Hatillo')
        break;

      case 34:
        query = query.where('city', '==', 'Hormigueros')
        break;

      case 35:
        query = query.where('city', '==', 'Humacao')
        break;

      case 36:
        query = query.where('city', '==', 'Isabela')
        break;

      case 37:
        query = query.where('city', '==', 'Jayuya')
        break;

      case 38:
        query = query.where('city', '==', 'Juana Díaz')
        break;
      
      case 39:
        query = query.where('city', '==', 'Juncos')
        break;

      case 40:
        query = query.where('city', '==', 'Lajas')
        break;

      case 41:
        query = query.where('city', '==', 'Lares')
        break;

      case 42:
        query = query.where('city', '==', 'Las Marías')
        break;

      case 43:
        query = query.where('city', '==', 'Las Piedras')
        break;

      case 44:
        query = query.where('city', '==', 'Loíza')
        break;

      case 45:
        query = query.where('city', '==', 'Luquillo')
        break;

      case 46:
        query = query.where('city', '==', 'Manatí')
        break;

      case 47:
        query = query.where('city', '==', 'Maricao')
        break;

      case 48:
        query = query.where('city', '==', 'Maunabo')
        break;

      case 49:
        query = query.where('city', '==', 'Mayagüez')
        break;

      case 50:
        query = query.where('city', '==', 'Moca')
        break;

      case 51:
        query = query.where('city', '==', 'Morovis')
        break;

      case 52:
        query = query.where('city', '==', 'Naguabo')
        break;

      case 53:
        query = query.where('city', '==', 'Naranjito')
        break;

      case 54:
        query = query.where('city', '==', 'Orocovis')
        break;

      case 55:
        query = query.where('city', '==', 'Patillas')
        break;

      case 56:
        query = query.where('city', '==', 'Peñuelas')
        break;

      case 57:
        query = query.where('city', '==', 'Ponce')
        break;

      case 58:
        query = query.where('city', '==', 'Quebradillas')
        break;

      case 59:
        query = query.where('city', '==', 'Rincón')
        break;

      case 60:
        query = query.where('city', '==', 'Río Grande')
        break;

      case 61:
        query = query.where('city', '==', 'Sabana Grande')
        break;

      case 62:
        query = query.where('city', '==', 'Salinas')
        break;

      case 63:
        query = query.where('city', '==', 'San Germán')
        break;

      case 64:
        query = query.where('city', '==', 'San Juan')
        break;
        

      case 65:
        query = query.where('city', '==', 'San Lorenzo')
        break;

      case 66:
        query = query.where('city', '==', 'San Sebastián')
        break;

      case 67:
        query = query.where('city', '==', 'Santa Isabel')
        break;

      case 68:
        query = query.where('city', '==', 'Toa Alta')
        break;

      case 69:
        query = query.where('city', '==', 'Toa Baja')
        break;

      case 70:
        query = query.where('city', '==', 'Trujillo Alto')
        break;

      case 71:
        query = query.where('city', '==', 'Utuado')
        break;

      case 72:
        query = query.where('city', '==', 'Vega Alta')
        break;

      case 73:
        query = query.where('city', '==', 'Vega Baja')
        break;

      case 74:
        query = query.where('city', '==', 'Vieques')
        break;

      case 75:
        query = query.where('city', '==', 'Villalba')
        break;

      case 76:
        query = query.where('city', '==', 'Yabucoa')
        break;

      case 77:
        query = query.where('city', '==', 'Yauco')
        break;

      default:

    }

  
    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 (
    <ScrollView>
    <View style={{ margin: 30 }}>
      <View style={{ width: '100%', alignItems: 'center' }}>
        <Text style={{ fontSize: 30, paddingBottom: 20 }}>Search</Text>
      </View>

      <Text style={{ fontSize: 20, paddingBottom: 10 }}>Interpreter city</Text>
      <SelectBox
        label="Select single"
        options={City}
        value={selectedCity}
        onChange={onChange()}
        hideInputFilter={false}
        arrowIconColor="#E4CD05"
        toggleIconColor='#E4CD05'
        searchIconColor='#E4CD05'


      />
      <Text style={{ fontSize: 20, paddingBottom: 10 }}>Interpreter Tags</Text>

      

      <SelectBox
        label="Select multiple"
        options={Tags}
        selectedValues={selectedTags}
        onMultiSelect={onMultiChange()}
        onTapClose={onMultiChange()}
        isMulti
        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,
        }}

          />


      {/* button that will fetch the users */}
      <Button title='Buscar' onPress={() => fetchUsers(selectedTags, selectedCity)}/>


      <FlatList
        numColumns={1}
        horizontal={false}
        data={users}
        
        renderItem={({ item, }) => {
          return (
          <View>
            <View style={{ flexDirection: "row", paddingBottom: 20, paddingTop: 20,  justifyContent: "space-between" }}>
              <Text>{item.data.username}</Text>
              <Text>{item.data.precio}</Text>
              <Button title='Buscar' onPress={() => { dothing(item.id, item.data.markedDates, item.data.push_token, u_token, item.data.username) }}/>
            </View>
            <View style={{ borderBottomColor: 'black', borderBottomWidth: 1 }} />
          </View>
          )
        }}
        />

    </View>
    </ScrollView>
  );

  function onMultiChange() {
    return (item) => setSelectedTags(xorBy(selectedTags, [item], 'id'))
  }

  function onChange(){
    return (item) => setSelectedCity(item)
  }
  
  function dothing(item_id, item_dates, i_token, u_token, I_username) {
    console.log('This is the item id: ', item_id, "With i_token: ", i_token, " u_token : ", u_token)
    console.log('These are the marked dates', item_dates)
    navigation.navigate('Calendar', {Intereprete_id: item_id, markedDates: item_dates, Flag: mapflag, I_Token: i_token, U_Token: u_token, Username: username, I_Username: I_username})
  } 

}

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




export default Search