<template>
  <div>
    <page-header class="d-flex justify-space-between">
      <span>
        {{ $t('learning.synonyms') }}
      </span>
    </page-header>

    <accordion-card disableAccordion>
      <v-row>
        <v-col cols="12" sm="12" md="3"></v-col>
        <v-col cols="12" sm="12" md="6">
          <v-chip
            v-for="(synonym, i) in synonyms"
            :key="`synonym-key${i}`"
            @click:close="askForDelete(synonym)"
            class="ma-2"
            color="secondary"
            close
          >
            {{ synonym.title }}
          </v-chip>
        </v-col>
        <v-col cols="12" sm="12" md="3"> </v-col>
      </v-row>

      <v-row>
        <v-col cols="12" sm="12" md="3">
          <v-subheader class="txt--text font-weight-black ml-10">
            Nieuw
          </v-subheader>
        </v-col>
        <v-col cols="12" sm="12" md="6">
          <v-text-field v-model="newSynonym" outlined v-on:keyup.enter="add">
          </v-text-field>
        </v-col>
        <v-col cols="12" sm="12" md="3"> </v-col>
      </v-row>
    </accordion-card>

    <v-dialog v-model="dialog" persistent max-width="740" v-if="itemSelected">
      <v-card class="primary pa-10" flat>
        <v-card-title class="headline">
          {{
            $t('learning.filters.delete_item_confirmation', {
              itemName: itemSelected.title || null,
            })
          }}
        </v-card-title>
        <v-card-actions>
          <div class="ma-4">
            <v-btn
              color="accent"
              class="mx-2"
              @click="deleteItem(itemSelected)"
              rounded
              depressed
              >{{ $t('general.delete') }}</v-btn
            >
            <v-btn class="mx-2" color="info" @click="close" rounded depressed>{{
              $t('general.cancel')
            }}</v-btn>
          </div>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import PageHeader from '~/components/UI/PageHeader/PageHeader'
import accordionCard from '@/components/UI/AccordionCard/AccordionCard'

export default {
  layout: `${process.env.CUSTOMER}Admin`,
  middleware: 'adminsOrOperators',
  components: {
    PageHeader,
    accordionCard,
  },
  data() {
    return {
      synonyms: [],
      newSynonym: '',
      dialog: false,
      itemSelected: null,
    }
  },
  async asyncData({ $axios }) {
    const response = await $axios.get('/synonyms')
    return { synonyms: response.data }
  },
  methods: {
    async add() {
      if (!this.newSynonym) return
      if (this.synonyms.includes(this.newSynonym)) return

      this.$nextTick(() => this.$nuxt.$loading.start())

      try {
        const response = await this.$axios.post(`/synonyms`, {
          title: this.newSynonym,
        })
        this.synonyms.push(response.data)
        this.newSynonym = ''
        this.$nuxt.$loading.finish()
        this.$notifier.showMessage({
          content: `Synonym '${this.newSynonym}' added`,
          color: 'success',
          icon: 'icon-message',
        })
      } catch (error) {
        console.log('add -> error', error)
        this.$nuxt.$loading.finish()
        this.$notifier.showMessage({
          content: `Error creating the filter item: ` + error.message,
          color: 'error',
          icon: 'icon-message',
        })
      }
    },

    close() {
      this.dialog = false
    },

    askForDelete(item) {
      this.itemSelected = item
      this.dialog = true
    },

    async deleteItem(synonym) {
      if (!synonym) {
        this.$notifier.showMessage({
          content: `No synonym to delete passed`,
          color: 'error',
          icon: 'icon-message',
        })
        return
      }

      const indexSynonym = this.synonyms.findIndex(
        (s) => s.title === synonym.title
      )

      if (indexSynonym === -1) return

      this.$nextTick(() => this.$nuxt.$loading.start())

      try {
        await this.$axios.delete(`/synonyms/${synonym.id}`)

        this.dialog = false
        this.itemSelected = null

        this.synonyms.splice(indexSynonym, 1)

        this.$nuxt.$loading.finish()

        this.$notifier.showMessage({
          content: `Synonym deleted`,
          color: 'success',
          icon: 'mdi-delete',
        })
      } catch (error) {
        this.dialog = false
        console.log('remove -> error', error)
        this.$nuxt.$loading.finish()

        this.$notifier.showMessage({
          content: `Error trying to delete the selected Synonym`,
          color: 'error',
          icon: 'mdi-delete',
        })
      }
    },
  },
}
</script>
