<script>
import PlainLabel from "~/components/atoms/label/PlainLabel";
import TextInput from "~/components/atoms/input/TextInput";
import PlainList from "~/components/atoms/list/PlainList";
import SuggestionInput from "~/components/atoms/input/SuggestionInput";

export default {
  components: {SuggestionInput, PlainList, TextInput, PlainLabel},
  props: {
    label: {default: ""},
    value: {default: ""},
    size: {default: "md"},
    placeholder: {default: ""},
    search_by: {default: item => item.text},
    is_disabled: {default: false},
    is_submitted: {default: false},
    is_error: {default: false},
    error_message: {default: []},
    options: {default: []},
    additional_class_group: {default: ""},
    additional_class_input: {default: ""},
    additional_class_label: {default: ""}
  },
  data: () => ({
    local_selected: {},
    inputClass: "",
  }),
  computed: {
    local_value: {
      get: function () {
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
      }
    }
  },
  watch: {
    is_error: function () {
      this.generateInputClass()
    },

    is_submitted: function (data) {
      this.generateInputClass()
    }
  },
  methods: {
    updateSelectedSuggestion(value) {
      this.local_selected = value
      this.$emit("input", value)
    },

    generateInputClass() {
      if (this.is_error && this.is_submitted) {
        this.inputClass = `is-invalid ${this.additional_class_input}`
      } else {
        this.inputClass = this.additional_class_input
      }
    },
  }
}
</script>
<template>
  <div :class="'form-group ' + additional_class_group">
    <plain-label :value="label" :is_bold="true" :additional_class="additional_class_label"/>
    <suggestion-input :options="options" v-model="local_value" :search_by="search_by" :additional_class="inputClass"/>
    <small class="text-danger" v-if="is_submitted && is_error">
      <plain-list v-for="(error, index) in error_message" v-if="!error.state" :key="index" additional_class="ml-3 my-1">
        {{ error.message }}
      </plain-list>
    </small>
  </div>
</template>
