<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<template>
  <div>
    <label for="searchText" class="form-label fw-bold">{{ label }}</label>
    <div class="row mb-2">
      <div class="col">
        <input
          autocomplete="off"
          type="text"
          class="form-control"
          id="searchText"
          v-model="searchText"
          @keyup="search()"
        />
      </div>
      <div class="col">
        <div v-if="selectedResult">
          <div v-if="type === 'contacttype'">
            <input
              type="text"
              class="form-control"
              id="contactContent"
              v-model="contactContent"
            />
          </div>
          <div v-if="type === 'language'">
            <select
              class="form-select"
              aria-label="Selektiere dein Level"
              v-model="level"
            >
              <option v-for="(value, key) in languagesSelection" :value="key" :key="key">{{value}}</option>
            </select>
          </div>
          <div v-else>
            <select
              class="form-select"
              aria-label="Selektiere dein Level"
              v-model="level"
            >
              <option v-for="(value, key) in levelSelection" :value="key" :key="key">{{value}}</option>
            </select>
          </div>
        </div>
      </div>
      <div class="col">
        <button
          v-if="selectedResult && !selectedResult.edit"
          type="button"
          class="btn btn-outline-success"
          aria-label="Hinzufügen"
          @click="addSelectedResult()"
        >
          <img
            src="/img/bootstrap-icons-1.5.0/plus-lg.svg"
            alt="Hinzufügen Icon"
          />
          Hinzufügen
        </button>
        <button
          v-if="selectedResult && selectedResult.edit"
          type="button"
          class="btn btn-outline-success"
          aria-label="Hinzufügen"
          @click="editSelectedResult()"
        >
          Änderung Speichern
        </button>
      </div>
    </div>
    <div class="" v-if="searchResults">
      <ul class="list-group">
        <li
          class="list-group-item"
          v-for="result in searchResults"
          :key="result.id"
          :class="{
            'bg-info':
              selectedResult &&
              selectedResult.id &&
              result.id === selectedResult.id,
          }"
          @click="selectedResult = result"
        >
          {{ result.name }}
        </li>
      </ul>
    </div>
    <profile-list
      :values="values"
      :type="type"
      :editable="true"
      @edit-value="editValue($event)"
      @remove-value="removeValue($event)"
    ></profile-list>
  </div>
</template>
<script>
import ProfileList from "@/components/ProfileList";

import levelJson from "@/assets/skill_level.json"
import languagesJson from "@/assets/language_level.json"

export default {
  name: "AutoComplete",
  components: {
    ProfileList,
  },
  props: {
    type: {
      type: String,
    },
    label: {
      type: String,
    },
    values: {
      type: Array,
    },
  },
  data() {
    return {
      iconUrl: this.apiUrl,
      searchText: "",
      contactContent: "",
      searchResults: [],
      showErrorMessage: false,
      level: "1",
      selectedResult: null,
      levelSelection: levelJson,
      languagesSelection: languagesJson,
    };
  },
  methods: {
    async search() {
      try {
        const request = await this.axios.get(
          `${this.apiUrl}/${this.type}s?search=${this.searchText}`,
          {
            headers: {
              Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
          }
        );
        if (request.status === 200) {
          this.searchResults = request.data[`${this.type}s`];
        }
      } catch (error) {
        console.error();
        this.showErrorMessage = true;
      }
    },
    addSelectedResult() {
      if (
        this.values
          .map((item) => item[this.type].id)
          .includes(this.selectedResult.id)
      ) {
        return false;
      }

      let changeValues = Object.assign(this.values);
      let newValue = {
        profile_id: localStorage.getItem("user_id"),
      };
      if (this.type != "contacttype") {
        newValue.level = this.level;
      } else {
        newValue.content = this.contactContent;
      }
      newValue[this.type] = this.selectedResult;
      changeValues.push(newValue);
      this.searchText = "";
      this.searchResults = [];
      this.selectedResult = null;
      this.level = 1;
      this.$emit("update-values", changeValues);
    },
    editSelectedResult() {
      this.values.map((item) => {
        if (item[this.type].name == this.selectedResult.name) {
          if (this.type != "contacttype") {
            item.level = this.level;
          } else {
            item.content = this.contactContent;
          }
        }
        return item;
      });

      this.$emit("update-values", this.values);
    },
    removeValue(valueId) {
      const newValues = this.values.filter((value) => {
        if (valueId === value[this.type].id) {
          return false;
        } else {
          return true;
        }
      });
      this.$emit("update-values", newValues);
    },
    editValue(value) {
      this.searchResults = [value[this.type]];
      this.selectedResult = {
        ...value[this.type],
        level: value.level,
        edit: true,
      };

      if (this.type != "contacttype") {
        this.level = value.level;
      } else {
        this.contactContent = value.content;
      }
      this.level = value.level;
    },
  },
};
</script>
