import React from 'react';
import PropTypes from 'prop-types';
import {
    ScrollView,
    Text, TextInput,
    View,
    LayoutAnimation,
    Platform,
    UIManager,
    ActivityIndicator
} from 'react-native';
import {Card, ButtonGroup} from 'react-native-elements';
import {connect} from "react-redux";
import Screen from "../../components/Screen";
import {companiesGetById, companiesSetShown} from "../../shared/actions/companies";
import {routesGetForGroup} from "../../shared/actions/routes";
import {pollsGet, pollsSend, pollsGetById} from "../../shared/actions/polls";
import {bindActionCreators} from "redux";
import RaisedButton from "../../components/RaisedButton";
import Moment from "moment/min/moment-with-locales";
import nl from "javascript-time-ago/locale/nl/index";
import {showMessage} from "react-native-flash-message/src/index";
import Icon from "react-native-vector-icons/EvilIcons";
import NavigationService from "../../shared/services/NavigationService";
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";

const textInputStyle = {
    borderWidth: 1, borderRadius: 5, borderColor: "#999",
    marginHorizontal: 10, marginVertical: 5, padding: 5
};
const questionStyle = {marginTop: 10};

class FeedbackDetailScreen extends Screen {
    state = {
        answers: {}
    };

    constructor() {
        super();
        Moment.locale("nl");

        if (Platform.OS === 'android') {
            UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);
        }
    }

    componentDidUpdate(oldState) {
        if (this.props.success && !oldState.success) {

            showMessage({
                message: "Feedback verstuurd, bedankt!",
                type: 'success'
            });
            NavigationService.navigate("feedback");
        }
    }

    updateAnswer(questionId, answer) {
        this.setState({
            answers: {
                ...this.state.answers,
                [questionId]: answer
            }
        });
    }

    renderRange(rules, index) {
        const options = [];
        for (let i = rules.min; i <= rules.max; ++i) {
            options.push(i);
        }

        const answer = this.state.answers[index];
        const answerIndex = options.findIndex(o => o === answer);

        return <ButtonGroup
            onPress={(value) => this.updateAnswer(index, options[value])}
            selectedIndex={answerIndex}
            buttons={options}
            selectedButtonStyle={{backgroundColor: "#008cd6"}}
            selectedTextStyle={{color: "white"}}
            containerStyle={{height: 50}}
        />
    }

    renderSelectOne(choices, index) {
        const answer = this.state.answers[index];
        const options = [];
        for (let i = 0; i < choices.length; ++i) {
            options.push(choices[i].title);
        }

        return <ButtonGroup
            onPress={(answer) => this.updateAnswer(index, answer)}
            selectedIndex={answer}
            buttons={options}
            selectedButtonStyle={{backgroundColor: "#008cd6"}}
            selectedTextStyle={{color: "white"}}
            containerStyle={{height: 50}}
        />
    }

    renderOpen(rules, index) {
        const answer = this.state.answers[index];
        if (answer === undefined) {
            setTimeout(() => this.setState({...this.state, answers: {...this.state.answers, [index]: null}}), 0);
        }

        return <TextInput multiline numberOfLines={1} style={textInputStyle} value={answer}
                          maxLength={rules.maxLength} onChangeText={value => this.updateAnswer(index, value)}
                          placeholder={"Vul hier je antwoord in."}/>
    }

    renderQuestionAnswerOptions(question, index) {
        switch (question.type) {
            case "range":
                return this.renderRange(question.rules, index);
            case "open":
                return this.renderOpen(question.rules, index);
            case "selectOne":
                return this.renderSelectOne(question.options, index);
        }
        return null;
    }

    submitAnswers() {
        this.props.pollsSend(this.props.auth.user.id, this.props.poll.id, Object.values(this.state.answers).map(a => isNaN(a) ? a : Number.parseInt(a)));
    }

    areAnswersValid(poll) {
        let valid = true;
        poll.poll.questions.forEach(question => {
            const index = this.props.poll.poll.questions.findIndex(q => q.id === question.id);

            if (question.type === "selectOne" || question.type === "selectMany" || question.type === "range") {
                if (!this.state.answers.hasOwnProperty("" + index)) {
                    valid = false;
                }
            }
        });
        return valid;
    }

    renderQuestion(question) {
        return <Card title={question.title} key={question.id}>
            <Text>{question.description}</Text>
            {this.renderQuestionAnswerOptions(question, this.props.poll.poll.questions.findIndex(q => q.id === question.id))}
        </Card>;
    }

    render() {
        const {poll} = this.props;

        return (
            <KeyboardAwareScrollView style={{flex: 1}}>
                {poll ? <View style={{marginBottom: 30}}>
                    <Card title={poll.poll.title} style={{padding: 0, alignItems: "center"}}>
                        <Text>{poll.poll.description || ""}</Text>
                    </Card>
                    {poll.poll.questions.map(q => this.renderQuestion(q))}
                    <RaisedButton style={{marginTop: 20}} disabled={this.props.loading || !this.areAnswersValid(poll)}
                                  onPress={() => this.submitAnswers()} title={"Verstuur"}/>
                </View> : null}
            </KeyboardAwareScrollView>);
    }
}

FeedbackDetailScreen.propTypes = {
    dispatch: PropTypes.func,
    navigation: PropTypes.object,
    auth: PropTypes.object
};

const mapStateToProps = (state) => {
    return {
        auth: state.auth,
        loading: state.polls.loading,
        poll: state.polls.lastLoaded,
        success: state.polls.success
    };
};

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        companiesGetById,
        pollsSend,
        pollsGet,
        pollsGetById,
        companiesSetShown,
        routesGetForGroup
    }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(FeedbackDetailScreen);
