<template>
  <v-row>
    <v-col>
      <div class="d-flex justify-space-between">
        <h2 class="ml-6 txt--text">
          {{ $t(`learning.filters.${filter.title}`) | capitalize }}
          ({{ filter.items.length }})
        </h2>
        <current-date-time showIcon class="mr-6" />
      </div>

      <accordion-card :title="$t('general.list') | capitalize">
        <v-row v-for="(item, index) in filter.items" :key="item.title + index">
          <v-col cols="12" sm="3" md="3">
            <v-subheader class="ml-10 txt--text font-weight-black"
              >{{ index + 1 }}.
            </v-subheader>
          </v-col>
          <v-col cols="12" sm="6" md="6">
            <v-text-field
              outlined
              :name="item.title + index"
              :value="item.title"
              append-icon="icon-close"
              @change="setDynamicTitle($event, index)"
              @click:append="askForDelete(item)"
              :append-outer-icon="
                hasItemChanges(index) ? 'mdi-content-save' : ''
              "
              @click:append-outer="update(item.id, index)"
              :error="hasItemChanges(index)"
            >
            </v-text-field>
          </v-col>
          <v-col cols="12" sm="3" md="3">
            <!-- <v-btn color="success" :to="`/manager/learning/filters/${slug}/${item.id}`">edit</v-btn> -->
          </v-col>
        </v-row>

        <v-row>
          <v-col cols="12" sm="12" md="3">
            <v-subheader class="ml-10 txt--text font-weight-black">
              Nieuw
            </v-subheader>
          </v-col>
          <v-col cols="12" sm="12" md="6">
            <v-text-field v-model="newItem" outlined> </v-text-field>
          </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-col>
          <v-col cols="12" sm="12" md="6">
            <v-btn
              class="cta-secondary"
              block
              depressed
              @click="addFilterItem"
              min-height="60px"
            >
              <v-icon x-small class="mx-4">icon-add</v-icon>

              {{ $t('general.add') | capitalize }}</v-btn
            >
          </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-card class="primary pa-10" flat>
          <v-card-title class="headline">
            {{
              $t('learning.filters.delete_item_confirmation', {
                itemName: itemSelected.title,
              })
            }}
          </v-card-title>
          <v-card-actions>
            <div class="ma-4">
              <v-btn
                color="accent"
                class="mx-2"
                @click="deleteItem(itemSelected.id)"
                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>
    </v-col>

    <v-footer fixed style="z-index: 4" height="90" color="primary">
      <v-btn text nuxt :to="localePath('/manager/learning/filters')">
        <v-icon>icon-arrow-left</v-icon>
      </v-btn>

      <!-- <v-btn
        v-cloak
        class="ma-2 white--text"
        color="accent"
        depressed
        rounded
        v-if="itemsHaveChanges"
        @click="saveAll"
      >
        SAVE</v-btn
      > -->
    </v-footer>
  </v-row>
</template>

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

import Vue from 'vue'

export default {
  layout: `${process.env.CUSTOMER}Admin`,
  middleware: 'adminsOrOperators',
  components: {
    accordionCard,
    PageHeader,
    currentDateTime,
  },
  data() {
    return {
      newItem: '',
      filter: { items: [] },
      items: [],
      itemSelected: {},
      dialog: false,
    }
  },
  mounted() {
    if (!this.isSlugNumber) this.$router.push('/manager')
    if (this.isNew) return
    if (this.isSlugNumber) this.getFilter(this.slug)
  },

  computed: {
    slug() {
      return this.$route.params.filter
    },
    isSlugNumber() {
      return !isNaN(this.slug.split(['-'], 1))
    },
    remoteItemsTitles() {
      if (!this.filter || !(this.filter.items.length > 0)) return []
      return this.filter.items.map(({ title }) => title)
    },
  },

  methods: {
    async getFilter(url) {
      if (!this.isSlugNumber) return

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

      try {
        const response = await this.$axios.get(`/filters/${url}`)

        this.filter = { ...response.data }

        this.items = response.data.items.map(({ title }) => title)

        this.$nuxt.$loading.finish()
      } catch (error) {
        this.$nuxt.$loading.finish()
        this.$notifier.showMessage({
          content: `Error getting the filter: ` + error.message,
          color: 'error',
          icon: 'icon-message',
        })
      }
    },

    async getFilters() {
      const response = await this.$axios.get('/filters')
      const filters = response.data
      await this.$store.commit('learning/SORT_FILTERS', filters)
    },

    async addFilterItem() {
      const data = {
        filter_id: this.filter.id,
        title: this.newItem,
      }
      this.$nextTick(() => this.$nuxt.$loading.start())

      try {
        await this.$axios.post(`/filter-items`, data)
        await this.getFilters()
        this.getFilter(this.slug)
        this.newItem = ''
        this.$nuxt.$loading.finish()
      } catch (error) {
        this.$nuxt.$loading.finish()
        this.$notifier.showMessage({
          content: `Error creating the filter item: ` + error.message,
          color: 'error',
          icon: 'icon-message',
        })
      }
    },

    setDynamicTitle(title, index) {
      Vue.set(this.items, index, title)
    },

    hasItemChanges(index) {
      return this.items[index] !== this.remoteItemsTitles[index]
    },

    close() {
      this.dialog = false
    },

    save() {
      this.close()
    },

    async update(id, index) {
      if (
        id === null ||
        id === undefined ||
        index === null ||
        index === undefined ||
        !this.items[index]
      )
        return

      const data = {
        id: id,
        title: this.items[index],
      }
      this.$nextTick(() => this.$nuxt.$loading.start())

      try {
        await this.$axios.post(`/filter-items`, data)

        await this.getFilters()
        this.getFilter(this.slug)
        this.$nuxt.$loading.finish()
        this.$notifier.showMessage({
          content: `Filter Item updated successfully`,
          color: 'success',
          icon: 'icon-message',
        })
      } catch (error) {
        this.$nuxt.$loading.finish()
        this.$notifier.showMessage({
          content: `Error updating the filter item: ` + error.message,
          color: 'error',
          icon: 'icon-message',
        })
      }
    },

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

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

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

      try {
        await this.$axios.delete(`/filter-items/${itemId}`)

        this.dialog = false
        this.itemSelected = {}

        await this.getFilter(this.slug)
        await this.getFilters()

        this.$nuxt.$loading.finish()

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

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

<style lang="scss" scoped>
.v-dialog >>> .v-cardcard__title {
  word-break: break-word;
}
</style>
