import React, { Component } from "react";
import { TextInput, TouchableWithoutFeedback, Keyboard, ImageBackground, Image, View, Text, Button } from "react-native";
import firebase from "firebase";
import { Calendar } from "react-native-calendars";
import { ScrollView } from "react-native-gesture-handler";
import SectionedMultiSelect from 'react-native-sectioned-multi-select';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Picker } from "@react-native-picker/picker";

import { fetchUser } from "../../redux/actions";
import { styles } from "../../config/styles";
import { availability } from "../../config/availability";

export class AvailabilityScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            //x : this.route.params.availabilityData.selectedItems,
            //y : this.route.params.availabilityData.markedDates,
            english: false,
            spanish: false,
            virtual: false,
            face_to_face: false,
            personal: false,
            group: false,
            city: 'San Juan',
            //cities: [],
            selectedItems: [],
            markedDates: {}
        };
        this.onSelectedItemsChange = this.onSelectedItemsChange.bind(this);
        this.onDaySelect = this.onDaySelect.bind(this);
        this.onSave = this.onSave.bind(this);
        this.handleUpdate = this.handleUpdate.bind(this);
    };

    componentDidMount(){
        /*if (x != undefined){
            this.setState({selectedItems : x});
        };
        if (y != undefined){
            this.setState({markedDates : y});
        }*/
        this.props.fetchUser();
        this.forceUpdate(() => {this.handleUpdate()})
    };

    handleUpdate(){
        const { currentUser } = this.props;
        if (currentUser != undefined){
            if (currentUser.hasOwnProperty('selectedItems') && currentUser.hasOwnProperty('markedDates') && currentUser.hasOwnProperty('city'))
            this.setState( {selectedItems: currentUser.selectedItems});
            this.setState( {markedDates: currentUser.markedDates});
            this.setState({city: currentUser.city})
        }
    };

    onSave(){
        const { selectedItems } = this.state;
    
        selectedItems.forEach((value) => {
            if(value === 'English'){
                this.setState({english : true}, () => firebase.firestore().collection('Interpreters').doc(firebase.auth().currentUser.uid).set({english : true}, {merge : true}));
            }
            else if(value === 'Spanish'){
                this.setState({spanish : true}, () => firebase.firestore().collection('Interpreters').doc(firebase.auth().currentUser.uid).set({spanish : true}, {merge : true}));
            }
            else if(value === 'Virtual'){
                this.setState({virtual : true}, () => firebase.firestore().collection('Interpreters').doc(firebase.auth().currentUser.uid).set({virtual : true}, {merge : true}));
            }
            else if(value === 'Face-to-Face'){
                this.setState({face_to_face : true}, () => firebase.firestore().collection('Interpreters').doc(firebase.auth().currentUser.uid).set({face_to_face : true}, {merge : true}));
            }
            else if(value === 'Personal Session'){
                this.setState({personal : true}, () => firebase.firestore().collection('Interpreters').doc(firebase.auth().currentUser.uid).set({personal : true}, {merge : true}));
            }
            else if(value === 'Group Session'){
                this.setState({group : true}, () => firebase.firestore().collection('Interpreters').doc(firebase.auth().currentUser.uid).set({group : true}, {merge : true}));
            }
            else if(!isNaN(value.charAt(0))){
                for (let key in this.state.markedDates) {
                    if(this.state.markedDates[key].hasOwnProperty('timeSlot')){
                        this.state.markedDates[key].timeSlot.push(value);
                    }
                    else{
                        this.state.markedDates[key].timeSlot = [];
                        this.state.markedDates[key].timeSlot.push(value);
                    }
                }
            }
            /*else{
                this.state.cities.push(value);
            }*/
        })
        firebase.firestore().collection('Interpreters')
            .doc(firebase.auth().currentUser.uid)
            .set(this.state, {merge : true})
            .then(() => {this.props.navigation.goBack()});
    };

    onSelectedItemsChange = (selectedItems) => {
        this.setState({selectedItems});
    };

    onDaySelect = (day) => {
        const selectedDay = day.dateString;
        let selected = true;

        if (this.state.markedDates[selectedDay]) {
            selected = !this.state.markedDates[selectedDay].selected;
        }
        const updatedMarkedDates = {...this.state.markedDates, ...{ [selectedDay]: { selected } } }
        this.setState({ markedDates : updatedMarkedDates });
    };

    render() {
        return (
            <ScrollView contentContainerstyle={styles.stdcontainer}>
                <Calendar
                    onDayPress={this.onDaySelect}
                    style={styles.calendar}
                    markedDates={this.state.markedDates}
                    theme={{selectedDayBackgroundColor: 'green'}}
                />
                <SectionedMultiSelect 
                    items={availability}
                    IconRenderer={Icon}
                    readOnlyHeadings={true}
                    uniqueKey='name'
                    subKey='children'
                    selectText='Choose your availability...'
                    onSelectedItemsChange={this.onSelectedItemsChange}
                    selectedItems={this.state.selectedItems}
                />
                <Picker selectedValue={this.state.city} onValueChange={(itemValue, itemIndex) => this.setState({city : itemValue})}>
                    <Picker.Item label='Adjuntas' value={'Adjuntas'}/>
                    <Picker.Item label='Aguada' value={'Aguada'}/>
                    <Picker.Item label='Adjuntas' value={'Adjuntas'}/>
                    <Picker.Item label='Aguadilla' value={'Aguadilla'}/>
                    <Picker.Item label='Aguas Buenas' value={'Aguas Buenas'}/>
                    <Picker.Item label='Aibonito' value={'Aibonito'}/>
                    <Picker.Item label='Arecibo' value={'Arecibo'}/>
                    <Picker.Item label='Arroyo' value={'Arroyo'}/>
                    <Picker.Item label='Añasco' value={'Añasco'}/>
                    <Picker.Item label='Barceloneta' value={'Barceloneta'}/>
                    <Picker.Item label='Barranquitas' value={'Barranquitas'}/>
                    <Picker.Item label='Bayamón' value={'Bayamón'}/>
                    <Picker.Item label='Cabo Rojo' value={'Cabo Rojo'}/>
                    <Picker.Item label='Caguas' value={'Caguas'}/>
                    <Picker.Item label='Camuy' value={'Camuy'}/>
                    <Picker.Item label='Canóvanas' value={'Canóvanas'}/>
                    <Picker.Item label='Carolina' value={'Carolina'}/>
                    <Picker.Item label='Cataño' value={'Cataño'}/>
                    <Picker.Item label='Cayey' value={'Cayey'}/>
                    <Picker.Item label='Ceiba' value={'Ceiba'}/>
                    <Picker.Item label='Ciales' value={'Ciales'}/>
                    <Picker.Item label='Cidra' value={'Cidra'}/>
                    <Picker.Item label='Coamo' value={'Coamo'}/>
                    <Picker.Item label='Comerío' value={'Comerío'}/>
                    <Picker.Item label='Corozal' value={'Corozal'}/>
                    <Picker.Item label='Culebra' value={'Culebra'}/>
                    <Picker.Item label='Dorado' value={'Dorado'}/>
                    <Picker.Item label='Fajardo' value={'Fajardo'}/>
                    <Picker.Item label='Florida' value={'Florida'}/>
                    <Picker.Item label='Guayama' value={'Guayama'}/>
                    <Picker.Item label='Guayanilla' value={'Guayanilla'}/>
                    <Picker.Item label='Guaynabo' value={'Guaynabo'}/>
                    <Picker.Item label='Gurabo' value={'Gurabo'}/>
                    <Picker.Item label='Guánica' value={'Guánica'}/>
                    <Picker.Item label='Hatillo' value={'Hatillo'}/>
                    <Picker.Item label='Hormigueros' value={'Hormigueros'}/>
                    <Picker.Item label='Humacao' value={'Humacao'}/>
                    <Picker.Item label='Isabela' value={'Isabela'}/>
                    <Picker.Item label='Jayuya' value={'Jayuya'}/>
                    <Picker.Item label='Juana Díaz' value={'Juana Díaz'}/>
                    <Picker.Item label='Juncos' value={'Juncos'}/>
                    <Picker.Item label='Lajas' value={'Lajas'}/>
                    <Picker.Item label='Lares' value={'Lares'}/>
                    <Picker.Item label='Las Marías' value={'Las Marías'}/>
                    <Picker.Item label='Las Piedras' value={'Las Piedras'}/>
                    <Picker.Item label='Loíza' value={'Loíza'}/>
                    <Picker.Item label='Luquillo' value={'Luquillo'}/>
                    <Picker.Item label='Manatí' value={'Manatí'}/>
                    <Picker.Item label='Maricao' value={'Maricao'}/>
                    <Picker.Item label='Maunabo' value={'Maunabo'}/>
                    <Picker.Item label='Mayagüez' value={'Mayagüez'}/>
                    <Picker.Item label='Moca' value={'Moca'}/>
                    <Picker.Item label='Morovis' value={'Morovis'}/>
                    <Picker.Item label='Naguabo' value={'Naguabo'}/>
                    <Picker.Item label='Naranjito' value={'Naranjito'}/>
                    <Picker.Item label='Orocovis' value={'Orocovis'}/>
                    <Picker.Item label='Patillas' value={'Patillas'}/>
                    <Picker.Item label='Peñuelas' value={'Peñuelas'}/>
                    <Picker.Item label='Ponce' value={'Ponce'}/>
                    <Picker.Item label='Quebradillas' value={'Quebradillas'}/>
                    <Picker.Item label='Rincón' value={'Rincón'}/>
                    <Picker.Item label='Rio Grande' value={'Rio Grande'}/>
                    <Picker.Item label='Sabana Grande' value={'Sabana Grande'}/>
                    <Picker.Item label='Salinas' value={'Salinas'}/>
                    <Picker.Item label='San Germán' value={'San Germán'}/>
                    <Picker.Item label='San Juan' value={'San Juan'}/>
                    <Picker.Item label='San Lorenzo' value={'San Lorenzo'}/>
                    <Picker.Item label='San Sebastián' value={'San Sebastián'}/>
                    <Picker.Item label='Santa Isabel' value={'Santa Isabel'}/>
                    <Picker.Item label='Toa Alta' value={'Toa Alta'}/>
                    <Picker.Item label='Toa Baja' value={'Toa Baja'}/>
                    <Picker.Item label='Trujillo Alto' value={'Trujillo Alto'}/>
                    <Picker.Item label='Utuado' value={'Utuado'}/>
                    <Picker.Item label='Vega Alta' value={'Vega Alta'}/>
                    <Picker.Item label='Vega Baja' value={'Vega Baja'}/>
                    <Picker.Item label='Vieques' value={'Vieques'}/>
                    <Picker.Item label='Villalba' value={'Villalba'}/>
                    <Picker.Item label='Yabucoa' value={'Yabucoa'}/>
                    <Picker.Item label='Yauco' value={'Yauco'}/>
                </Picker>
                <Button title='Save' onPress={() => {this.onSave()}}/>
            </ScrollView>
        );
    }
}

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