<template>
  <v-row>
    <v-col>
      <div class="d-flex justify-space-between">
        <h2 class="ml-6 txt--text">Branches ({{ 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 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"
              @change="setDynamicTitle($event, index)"
              append-icon="icon-close"
              @click:append="askForDelete(item)"
              @click:append-outer="update(item.id, index)"
              :append-outer-icon="
                hasItemChanges(index) ? 'mdi-content-save' : ''
              "
              :error="hasItemChanges(index)"
            >
            </v-text-field>
          </v-col>
          <v-col cols="12" sm="3" md="3"> </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"
              min-height="60px"
              block
              depressed
              @click="addBranch"
              :disabled="!newItem"
            >
              <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-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: 'allowSuperAdminOrAdmin',
  components: {
    accordionCard,
    PageHeader,
    currentDateTime,
  },
  data() {
    return {
      newItem: '',
      branches: [],
      items: [],
      itemsRemote: [],
      itemSelected: {},
      dialog: false,
    }
  },
  async mounted() {
    await this.getBranches()
  },

  computed: {},
  methods: {
    async getBranches() {
      const response = await this.$axios.get('/members/branches')
      this.items = [...response.data]
      this.itemsRemote = [...response.data]
    },
    close() {
      this.dialog = false
    },
    save() {
      this.close()
    },
    hasItemChanges(index) {
      return this.items[index].title !== this.itemsRemote[index].title
    },
    setDynamicTitle(title, index) {
      this.items[index] = Object.assign({}, { ...this.items[index], title })
      Vue.set(this.items, index, this.items[index])
    },

    async addBranch() {
      const data = { title: this.newItem }

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

      try {
        await this.$axios.post(`/members/branches`, data)
        await this.getBranches()
        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',
        })
      }
    },

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

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

      try {
        await this.$axios.post(`/members/branches`, this.items[index])

        await this.getBranches()
        this.$nuxt.$loading.finish()
        this.$notifier.showMessage({
          content: `Branch updated successfully`,
          color: 'success',
          icon: 'icon-message',
        })
      } catch (error) {
        this.$nuxt.$loading.finish()
        this.$notifier.showMessage({
          content: `Error updating the Branch: ` + 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(`/members/branches/${itemId}`)

        this.dialog = false
        this.itemSelected = {}

        await this.getBranches()

        this.$nuxt.$loading.finish()

        this.$notifier.showMessage({
          content: `Branch 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 Branch`,
          color: 'error',
          icon: 'mdi-delete',
        })
      }
    },
  },
}
</script>
