<template>
  <div>
    <styled-input label="Titre" v-model="title" />
    <styled-input label="Description" v-model="subTitle" />
    <div>
      <div class="formcontrol-label">Type de question</div>
      <button
        class="btn-group small left"
        :class="{ selected: type == 'competence' }"
        @click="type = 'competence'"
      >
        Options
      </button>
      <button
        class="btn-group small right"
        :class="{ selected: type == 'text' }"
        @click="type = 'text'"
      >
        Text libre
      </button>
      <button
        style="margin-left: 8px"
        class="btn-group small left"
        :class="{ selected: mandatory }"
        @click="mandatory = true"
      >
        Obligatoire
      </button>
      <button
        class="btn-group small right"
        :class="{ selected: mandatory == false }"
        @click="mandatory = false"
      >
        Facultative
      </button>
    </div>
    <div v-if="type == 'competence'">
      <chips-input
        label="Ajouter une option"
        placeholder="Choisir une option"
        secondary-placeholder="+ option"
        :autocompleteList="autocompleteList"
        :strict-autocomplete="true"
        v-model="competenceIdList"
      />
      <styled-input
        v-for="(c, idx) in competences"
        :key="idx"
        :helpText="competenceLabel(c.id)"
        :modelValue="c.text"
        @input="updateCompetenceText($event, idx)"
      />
      <styled-input v-if="mandatory" helpText="Réponse par défaut" v-model="mandatoryText" />
      <button class="btn small error" @click="$emit('delete')">
        <i class="material-icons">delete_forever</i>Supprimer
      </button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from "vue";
import { Question, QuestionCompetence, QuestionType } from "@/models/Questionnaire";

import styledInput from "@/components/input.vue";
import chipsInput from "@/components/SelectChipInput.vue";
import Competence from "@/models/Competence";
import AutocompleteValues from "@/models/AutocompleteOptions";
import "@/assets/css/button-group.css";

export default defineComponent({
  components: { styledInput, chipsInput },
  data() {
    return {
      title: "",
      subTitle: "",
      type: "competence" as QuestionType,
      mandatory: false,
      mandatoryText: "",
      competences: [] as Array<QuestionCompetence>,
      competenceIdList: [] as Array<string>,
    };
  },
  props: {
    modelValue: {
      type: Object as PropType<Question>,
      default: () => ({
        title: "",
        subTitle: "",
        type: "competence",
        mandatory: false,
        competenceList: [] as Array<string>,
        order: -1,
      }),
    },
    potentialCompetences: {
      type: Array as PropType<Array<Competence>>,
      default: () => [],
    },
  },
  watch: {
    modelValue: {
      handler() {
        this.updateValue();
      },
      deep: true,
    },
    competenceIdList(val: Array<string>) {
      const ids = val.map((i) => parseInt(i));
      if (val.length != this.competences.length) {
        this.competences = this.competences.filter((c) => ids.includes(c.id));
        if (ids.length > this.competences.length) {
          const existingId = this.competences.map((c) => c.id);
          ids
            .filter((i) => !existingId.includes(i))
            .forEach((id) =>
              this.competences.push({
                id,
                text: this.potentialCompetences.find((c) => c.id == id)?.name ?? "",
              })
            );
        }
        this.updateParent();
      }
    },
    title(val: string) {
      if (val != this.modelValue.title) this.updateParent();
    },
    subTitle(val: string) {
      if (val != this.modelValue.subTitle) this.updateParent();
    },
    type(val: string) {
      if (val != this.modelValue.type) this.updateParent();
    },
    mandatory(val: boolean) {
      if (val != this.modelValue.mandatory) this.updateParent();
    },
    mandatoryText(val: string) {
      if (val != this.modelValue.mandatoryText) this.updateParent();
    },
  },
  methods: {
    updateValue() {
      const val = this.modelValue;
      if (this.title != val.title) this.title = val.title;
      if (this.subTitle != val.subTitle) this.subTitle = val.subTitle;
      if (this.type != val.type) this.type = val.type;
      if (this.mandatory != val.mandatory) this.mandatory = val.mandatory;
      if (this.mandatoryText != val.mandatoryText) this.mandatoryText = val.mandatoryText;
      if (
        this.competences
          .map((c) => c.id)
          .sort()
          .join("") !=
        val.competenceList
          .map((c) => c.id)
          .sort()
          .join("")
      )
        this.competences = val.competenceList;
      this.competenceIdList = this.competences.map((i) => i.id.toString());
    },
    updateParent() {
      const newQ: Question = {
        evtUuid: this.modelValue.evtUuid,
        uuid: this.modelValue.uuid,
        order: this.modelValue.order,
        title: this.title,
        subTitle: this.subTitle,
        type: this.type,
        mandatory: this.mandatory,
        competenceList: this.competences,
        mandatoryText: this.mandatoryText,
      };
      this.$emit("update:modelValue", newQ);
    },
    updateCompetenceText(e: InputEvent, idx: number) {
      const newVal = (e.target as HTMLInputElement).value;
      if (newVal != this.competences[idx].text) {
        this.competences[idx].text = newVal;
        this.updateParent();
      }
    },
    competenceLabel(id: number): string {
      return this.potentialCompetences.find((c) => c.id == id)?.name ?? "";
    },
  },
  computed: {
    autocompleteList(): Array<AutocompleteValues> {
      return this.potentialCompetences.map((o) => ({ id: o.id.toString(), name: o.name }));
    },
  },
  mounted() {
    this.updateValue();
  },
});
</script>

<style scoped></style>
