<script>
    import axios from 'axios'
    import Config from '@/config.js'
    import { useQuestionStore } from '@/stores/questions.js'
    import { useAnswersStore } from '@/stores/answers.js'
    import { useResultsStore } from '@/stores/results.js'
    import Content from '@/components/Content.vue'
    import Header from '@/components/Header.vue'
    import TextFrame from '@/components/TextFrame.vue'
    import ArrowLeftBold from '@/components/icons/ArrowLeftBold.vue'
    import ArrowRightBold from '@/components/icons/ArrowRightBold.vue'
    import FleurDeLis from '@/components/icons/FleurDeLis.vue'
    
    export default {
        setup() {
            const questionStore = useQuestionStore()
            const answersStore = useAnswersStore()
            const resultsStore = useResultsStore()

            return {
                questionStore,
                answersStore,
                resultsStore
            }
        },
        components: {
            ArrowLeftBold,
            ArrowRightBold,
            Content,
            FleurDeLis,
            Header,
            TextFrame
        },
        created() {
            this.answersStore.makeArray(this.id, this.questionStore.questions[this.id].select)
        },
        mounted() {
            this.answersStore.quizCurrent = this.id
            this.$watch(
                () => this.$route.params, (toParams, previousParams) => {
                    if (this.$route.name == 'Question') {
                        if (toParams.id >= this.questionStore.questions.length || this.id < 0) {
                            this.$router.push('/err_notfound')
                        } else {
                            this.answersStore.quizCurrent = toParams.id
                        }
                    }
                }
            )
            this.$watch(
                () => this.questionStore.questions, (newValue) => {
                    if (this.id >= this.questionStore.questions.length || this.id < 0) {
                        this.$router.push('/err_notfound')
                    } else {
                        this.answersStore.makeArray(this.id, this.questionStore.questions[this.id].select)
                    }
                }
            )
        },
        methods: {
            submitAnswers() {
                const data = JSON.stringify(this.answersStore.answers) 
                axios.post(
                    `${Config.SERVER}api/submit/`,
                    data,
                    {
                       headers: {
                        'Content-Type': 'application/json'
                       } 
                    }
                ).then( (response) => {
                    console.log('Submitted answers.')
                    this.resultsStore.store('results', response.data)
                    console.log('Results fetched from the server.')
                    this.answersStore.quizCurrent = null
                    this.$router.push('/results')
                }).catch( (error) => {
                    console.log(error)
                    this.$router.push('/err_refused')
                })
            }
        },
        props: {
            id: {
                type: Number,
                required: true
            }
        }
    }
</script>

<template>
    <TextFrame>
        <Header>
            Take the Quiz
        </Header>
        <Content>
            <div v-if="questionStore.questions[this.id]">
                <article class="prose">
                    <h3>Question {{ this.id + 1}}</h3>
                    <div v-html="questionStore.questions[this.id].question"/>
                </article>
                <div class="grid grid-cols-1 content-evenly items-center gap-2 justify-center my-12 mx-auto md:grid-cols-2 lg:grid-cols-3" :aria-multiselectable="questionStore.questions[this.id].select > 1 ? true: false">
                    <div v-for="(answer, index) in questionStore.questions[this.id].answers" :key="`q${this.id}-o${index}`" class="inline-flex">
                        <input :type="this.questionStore.questions[this.id].select > 1 ? 'checkbox' : 'radio'" class="checkbox" :id="`q${this.id}-o${index}`" :value=index :key="`q${this.id}-o${index}`" v-model="answersStore.answers[this.id]" :disabled="this.questionStore.questions[this.id].select > 1 && this.answersStore.answers[this.id].length == this.questionStore.questions[this.id].select && !this.answersStore.answers[this.id].includes(index)">
                        <label :for="`q${this.id}-o${index}`">
                            <div v-html="answer" class="w-full h-full p-2 select-none transition-all duration-100 ease-in-out hover:bg-lime-200 hover:text-orange-600 hover:cursor-pointer" :aria-label="answer" :title="answer"></div>
                        </label>
                    </div>
                </div>
                <div class="w-full flex mx-auto items-center justify-between max-w-sm">
                    <router-link :to="`/quiz/question/${this.id-1}`" v-if="this.id > 0">
                        <div class="inline-flex h-full px-3 py-1 space-x-1 rounded-md bg-olive-800 text-white items-center transition-all duration-300 ease-in-out hover:bg-olive-600" title="Back">
                            <span class="scale-100">
                                <ArrowLeftBold/>
                            </span>
                            <span class="uncial-antiqua">Back</span>
                        </div>
                    </router-link>
                    <div class="inline-flex h-full px-3 py-1 space-x-1 rounded-md bg-olive-800 opacity-50 text-white items-center hover:cursor-not-allowed" v-else>
                        <span class="scale-100">
                            <ArrowLeftBold/>
                        </span>
                        <span class="uncial-antiqua">Back</span>
                    </div>
                    <router-link :to="`/quiz/question/${this.id+1}`" v-if="this.id < this.questionStore.questions.length - 1 && this.answersStore.isAnswered(this.id)">
                        <div class="inline-flex h-full px-3 py-1 space-x-1 rounded-md bg-olive-800 text-white items-center transition-all duration-300 ease-in-out hover:bg-olive-600" title="Next">
                            <span class="uncial-antiqua">Next</span>
                            <span class="scale-100">
                                <ArrowRightBold/>
                            </span>
                        </div>
                    </router-link>
                    <div class="inline-flex h-full px-3 py-1 space-x-1 rounded-md bg-olive-800 opacity-50 text-white items-center hover:cursor-not-allowed" v-else>
                        <span class="uncial-antiqua">Next</span>
                        <span class="scale-100">
                            <ArrowRightBold/>
                        </span>
                    </div>
                </div>
                <Transition
                    enter-active-class="transition-all duration-300 origin-center ease-in"
                    enter-from-class="transform opacity-0 md:scale-95"
                    leave-active-class="transition-all duration-300 origin-center ease-out"
                    leave-to-class="transform opacity-0 md:scale-95"
                    >
                    <div v-show="this.id == this.questionStore.questions.length -1 && this.answersStore.isAnswered(this.id)" class="mx-auto my-8 w-fit transition-all">
                        <button @click="this.submitAnswers()">
                            <div class="inline-flex px-3 py-1 space-x-2 rounded-md bg-olive-800 text-white transition-all duration-300 ease-in-out hover:bg-olive-600">
                                <span class="scale-75">
                                    <FleurDeLis/>
                                </span>
                                <span class="uncial-antiqua">Submit Answers</span>
                                <span class="scale-75">
                                    <FleurDeLis/>
                                </span>
                            </div>
                        </button>
                    </div>
                </Transition>
            </div>
            <div v-else>
                Loading
            </div>
        </Content>
    </TextFrame>
</template>

<style scoped>
    .checkbox {
        position: absolute;
        opacity: 0;
    }

    :focus + label>div {
        @apply bg-lime-200;
        @apply text-orange-600;
    }

    :checked + label>div {
        @apply border-olive-600;
        @apply border-solid;
        @apply border-l-2;
        @apply text-orange-600;
    }
    :not(:checked):disabled + label>div {
        @apply opacity-50;
        @apply cursor-not-allowed;
        @apply hover:bg-inherit;
        @apply hover:text-inherit;
    }
    :checked:disabled + label>div {
        @apply border-2;
        @apply border-olive-600;
        @apply border-solid;
    }
</style>