<template>
    <section class="assessmentSection" v-show="section.visible">

      <header class="sectionHeader" v-if="showSectionHeader">
          <h2
                  class="sectionTitle"
                  v-html="section.title"
          ></h2>
      </header>

      <template v-if="section.product_selection">

          <template>
              <product-listings
                      :selectionEnabled="true"
                      :products="productGroups[0]"
                      @option-changed="validate"
                      v-if="productGroups[0]"

              />
          </template>


      </template>

      <template v-else-if="section.product_confirmation">


          <template v-for="(products) in selectedProductGroups">

              <product-listings
                      :selectionEnabled="false"
                      :products="products"
                      @option-changed="validate"
              />

          </template>


      </template>

      <template v-else>

          <template v-for="(question, index) in section.questions">


              <question-wrap
                      :question-id="question.id"
                      v-if="isQuestion(question)"
                      :key="'qwrap' + question.id"
                      ref="questionWrap"
                      :question-number="question.number"
              />

              <warning-wrap
                      :question-id="0"
                      v-if="question.custom_error?.length"
                      :custom-error="question.custom_error"
              />


              <warning-wrap
                      :question-id="question.id"
                      v-else-if="isWarning(question)"
                      :key="'wwrap' + question.id"
              />

              <markup-wrap
                      :question-id="question.id"
                      v-else-if="isHTML(question)"
                      :key="'mwrap' + question.id"
              />


          </template>

      </template>

      <footer class="sectionFooter">

          <button
                  type="button"
                  class="button"
                  @click.prevent="updateSection()"
                  :disabled="proceedButtonDisabled"
                  v-html="proceedButtonText"
                  v-if="!section.product_selection"
          ></button>



      </footer> <!-- .assessmentButtons -->

  </section>

</template>

<script>

import { mapGetters } from 'vuex';
import { debounce, isUndefined } from 'lodash';

import questionWrap from './question_wrap';
import warningWrap from './warning_wrap';
import markupWrap from './markup_wrap';
import productListings from './product_listings';
import collapseArea from './collapse_area';


export default {
    name: "formSection",
    components: {
        questionWrap,
        warningWrap,
        markupWrap,
        productListings,
        collapseArea
    },
    props: {
        section: {
            type: [Object, Array, Boolean],
            default (rawProps) {
                return [];
            }
        },
        showSectionHeader: {
            type: [Boolean],
            default (rawProps) {
                return false;
            }
        },
    },
    data() {
        return {
            productsSelected: false,
            selectedItems: {}
        }
    },
    watch: {
        'section.visible': function() {
            if(this.section.product_selection || this.section.product_confirmation) {
                EventBus.$emit('assessmentStep', 2);
            }else{
                EventBus.$emit('assessmentStep', 1);
            }
        }
    },
    computed: {
        ...mapGetters({
            productGroups: 'getAssessmentProducts',
            selectedProductGroups: 'getAssessmentSelectedProducts',
            proceedButtonText: 'getAssessmentSectionNextStepText'
        }),

        proceedButtonDisabled() {

            if(this.section.product_selection) {

                if(!this.productsSelected) {
                    return true;
                }

            }else if(!isUndefined(this.section.loading)) {

                if(this.section.loading) {
                    return true;
                }

            }

            return false;

        },
    },
    methods: {

        isQuestion(question) {
            return question.is_a_question;
        },

        isWarning(question) {
            return ['error', 'alert', 'success'].indexOf(question.question_type) > -1;
        },

        isHTML(question) {
            return question.question_type == 'html';
        },

        updateSection: debounce(function() {

            this.validate();
            this.$emit('update-section', this.section);

        }, 200),

        validate() {

            let canProceed = true;

            let questionWrap = this.$refs.questionWrap;

            if(this.section.product_selection) {
                if(!this.hasSelectedItems()) {
                    this.productsSelected = false;
                    canProceed = false;
                }else{
                    this.productsSelected = true;
                }
            }else {

                //Force validation on all questions
                if (questionWrap !== undefined && questionWrap.length) {

                    questionWrap.forEach(questionWrap => {
                        questionWrap.externalValidation();
                    });

                    // Hidden questions must not block progression — only
                    // visible questions count towards the proceed check.
                    let invalidQuestions = this.section.questions.filter(question => question.visible && !question.can_proceed);

                    if (invalidQuestions.length) {
                        canProceed = false;

                        let firstInvalid = invalidQuestions[0];
                        let targetID = 'question_wrap_' + firstInvalid.id;

                        document.getElementById(targetID).scrollIntoView({
                            behavior: 'smooth'
                        });
                    }

                }

            }


            this.section.can_proceed = canProceed;

            return this.section;

        },

        hasSelectedItems() {

            let selected = {};

            let selectedItems = 0;

            for(const prop in selected) {

                if(Object.keys(selected[prop]).length) {
                    selectedItems++;
                }

            }


            return selectedItems > 0;

        },
    }
}
</script>

<style lang="less">

    @import '@site/css/variables.less';
    @import '@core/css/mixins.less';
    @import '@site/../default/css/base/mixins.less';

    .assessmentSection {

        width: 100%;


        @media all and (max-width: 1020px) {
            max-width: 100%;
        }

        .sectionTitle {
            .rems(20);
            line-height: 1.2em;
            font-weight: 700;
            margin: 0 0 24px;
        }

        .sectionFooter {
            padding: 27px 0 0;
            display: flex;
            gap: 16px;

            .button {
                &:last-of-type {
                    margin-left: auto;
                }
            }
        }

        .button {
            margin: 0;
            min-width: 216px;

            @media all and (max-width: 800px) {
                width: 100%;
                max-width: 100%;
            }
        }

    }



</style>
