<template>
  <accordion-card :title="$t('learning.product_overview.version')">
    <v-data-table
      :headers="headers"
      :items="versions"
      :options="options"
      hide-default-footer
      item-key="version"
      v-if="hasVersions"
      flat
    >
      <template v-slot:item.made_by="{ item }">
        {{ getFilterItem('made_by', item).title }}
      </template>
      <template v-slot:item.dev_environment="{ item }">
        {{ getFilterItem('dev_environment', item).title }}
      </template>

      <template v-slot:item.status="{ item }">
        <v-icon
          x-small
          class="mr-2"
          v-if="getFilterItem('status', item).color"
          :color="getFilterItem('status', item).color"
          >mdi-circle</v-icon
        >
        {{ getFilterItem('status', item).title }}
      </template>

      <template v-slot:item.release_start="{ item }">
        {{ formatDate(item.release_start) }}
      </template>

      <template v-slot:item.release_end="{ item }">
        {{ formatDate(item.release_end) }}
      </template>

      <template v-slot:item.actions="{ item }">
        <v-btn
          class="mx-4 white--text view"
          style="height: 100%"
          :color="$vuetify.theme.dark ? 'info' : 'txt'"
          rounded
          depressed
          small
          @click="viewItem(item)"
          >{{ $t('general.view') }}</v-btn
        >

        <v-menu
          offset-y
          v-if="
            editMode && ($store.getters.isAdmin || $store.getters.isOperator)
          "
        >
          <template v-slot:activator="{ on }">
            <v-hover v-slot:default="{ hover }">
              <v-btn
                :color="hover ? 'info' : ''"
                :outlined="hover"
                depressed
                fab
                small
                v-on="on"
              >
                <v-icon>icon-options</v-icon>
              </v-btn>
            </v-hover>
          </template>
          <v-list width="200">
            <v-list-item @click="editItem(item)">
              <v-list-item-icon class="mr-1">
                <v-icon small>icon-edit</v-icon>
              </v-list-item-icon>

              <v-list-item-content>
                <v-list-item-subtitle>{{
                  $t('general.edit') | capitalize
                }}</v-list-item-subtitle>
              </v-list-item-content>
            </v-list-item>

            <v-dialog max-width="740" persistent v-model="dialogDelete">
              <template v-slot:activator="{ on }">
                <v-list-item v-on="on">
                  <v-list-item-icon class="mr-1">
                    <v-icon small>icon-remove</v-icon>
                  </v-list-item-icon>

                  <v-list-item-content>
                    <v-list-item-subtitle>{{
                      $t('general.delete') | capitalize
                    }}</v-list-item-subtitle>
                  </v-list-item-content>
                </v-list-item>
              </template>
              <v-card class="primary pa-10" flat>
                <v-card-title class="headline">
                  {{
                    $t('learning.product_overview.delete_confirmation', {
                      productName: item.version_number,
                    })
                  }}
                </v-card-title>
                <v-card-actions>
                  <div class="ma-4">
                    <v-btn
                      @click="deleteItem(item)"
                      class="mx-2"
                      color="accent"
                      depressed
                      rounded
                      >{{ $t('general.delete') }}</v-btn
                    >
                    <v-btn
                      @click="dialogDelete = false"
                      class="mx-2"
                      color="info"
                      depressed
                      rounded
                      >{{ $t('general.cancel') }}</v-btn
                    >
                  </div>
                </v-card-actions>
              </v-card>
            </v-dialog>
          </v-list>
        </v-menu>
      </template>
    </v-data-table>

    <v-dialog
      v-model="dialogVersion"
      max-width="75%"
      v-if="$store.getters.isAdmin || $store.getters.isOperator"
    >
      <template v-slot:activator="{ on, attrs }">
        <v-btn
          v-if="editMode"
          class="cta-secondary my-10"
          block
          depressed
          min-height="60px"
          :disabled="isCreateMode"
          v-on="on"
          @click="resetVersionsFilters"
        >
          <v-icon x-small class="mx-4">icon-add</v-icon>

          {{ $t('learning.add_new_version') }}</v-btn
        >
      </template>
      <v-form ref="form" v-model="valid" lazy-validation>
        <v-card ref="card">
          <v-card-title>
            <span class="headline">{{ formTitle }}</span>
            <!-- <input ref="input" /> -->
          </v-card-title>

          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12" sm="12" md="3">
                  <v-subheader class="txt--text font-weight-black">{{
                    $t('learning.versions.version_number')
                  }}</v-subheader>
                </v-col>
                <v-col cols="12" sm="12" md="9">
                  <v-text-field
                    v-model="editedItem.version_number"
                    :outlined="editModeComputed"
                    :solo="!editModeComputed"
                    :disabled="!editModeComputed"
                    :flat="!editModeComputed"
                    :rules="rules.version_number"
                    required
                    error
                  ></v-text-field>
                </v-col>
              </v-row>

              <v-row
                v-for="(filterTitle, i) in filterInputs"
                :key="`row-filter-${i}`"
              >
                <v-col cols="12" sm="12" md="3">
                  <v-subheader class="txt--text font-weight-black">{{
                    $t(`learning.filters.${filterTitle}`)
                  }}</v-subheader>
                </v-col>
                <v-col cols="12" sm="12" md="9">
                  <universalFilterSelector
                    :filterTitle="filterTitle"
                    :editMode="editModeComputed"
                    target="versions"
                    :key="`universal-filter-version-${i}`"
                  />
                </v-col>
              </v-row>

              <v-row>
                <v-col cols="12" sm="12" md="3">
                  <v-subheader class="txt--text font-weight-black">
                    {{ $t('learning.versions.release_date.from') }}
                  </v-subheader>
                </v-col>
                <v-col cols="12" sm="12" md="9" class="d-flex">
                  <v-menu
                    ref="menuStart"
                    v-model="menuStart"
                    :close-on-content-click="false"
                    transition="scale-transition"
                    offset-y
                    min-width="290px"
                  >
                    <template v-slot:activator="{ on, attrs }">
                      <!-- <input type="text" v-model="startData" /> -->

                      <v-text-field
                        :name="`release-start-date-${Math.random()}`"
                        v-model="computedDateFormattedStart"
                        max-height="100px"
                        v-bind="attrs"
                        v-on="on"
                        :outlined="editModeComputed"
                        :solo="!editModeComputed"
                        :disabled="!editModeComputed"
                        :flat="!editModeComputed"
                        :rules="rules.release_start"
                        required
                        error
                        readonly
                      >
                        <template v-slot:append>
                          <v-icon v-on="on">icon-events</v-icon>
                        </template>
                      </v-text-field>
                    </template>
                    <v-date-picker
                      v-model="editedItem.release_start"
                      no-title
                      scrollable
                      :disabled="!editModeComputed"
                      :flat="!editModeComputed"
                      locale="nl-NL"
                    >
                      <v-spacer></v-spacer>
                      <v-btn text @click="menuStart = false">Cancel</v-btn>
                      <v-btn
                        text
                        @click="$refs.menuStart.save(editedItem.release_start)"
                        >OK</v-btn
                      >
                    </v-date-picker>
                  </v-menu>
                  <span class="mx-5 my-3 font-weight-bold">
                    {{ $t('learning.versions.release_date.to') }}
                  </span>
                  <v-menu
                    ref="menuEnd"
                    v-model="menuEnd"
                    :close-on-content-click="false"
                    transition="scale-transition"
                    offset-y
                    min-width="290px"
                  >
                    <template v-slot:activator="{ on, attrs }">
                      <v-text-field
                        :name="`release-end-date-${Math.random()}`"
                        v-model="computedDateFormattedEnd"
                        :outlined="editModeComputed"
                        :solo="!editModeComputed"
                        :disabled="!editModeComputed"
                        :flat="!editModeComputed"
                        max-height="100px"
                        v-bind="attrs"
                        v-on="on"
                        clearable
                        readonly
                      >
                        <template v-slot:append>
                          <v-icon v-on="on">icon-events</v-icon>
                        </template>
                      </v-text-field>
                    </template>
                    <v-date-picker
                      v-model="editedItem.release_end"
                      no-title
                      scrollable
                      :disabled="!editModeComputed"
                      :flat="!editModeComputed"
                      locale="nl-NL"
                    >
                      <v-spacer></v-spacer>
                      <v-btn text @click="menuEnd = false">Cancel</v-btn>
                      <v-btn
                        text
                        @click="$refs.menuEnd.save(editedItem.release_end)"
                        >OK</v-btn
                      >
                    </v-date-picker>
                  </v-menu>
                </v-col>
              </v-row>

              <v-row>
                <v-col cols="12" sm="12" md="3">
                  <v-subheader class="txt--text font-weight-black">{{
                    $t('learning.versions.release_planning')
                  }}</v-subheader>
                </v-col>
                <v-col cols="12" sm="12" md="9">
                  <quill-editor
                    class="quill primary"
                    :options="editorOption"
                    v-model="editedItem.release_planning_description"
                    v-if="editModeComputed"
                  />
                  <span
                    v-html="editedItem.release_planning_description"
                    v-else
                  ></span>
                </v-col>
              </v-row>

              <v-row class="mb-10">
                <v-col cols="12" sm="12" md="3">
                  <v-subheader class="txt--text font-weight-black">{{
                    $t('learning.versions.technical_information')
                  }}</v-subheader>
                </v-col>
                <v-col cols="12" sm="12" md="9">
                  <quill-editor
                    class="quill primary"
                    v-model="editedItem.technical_information"
                    :options="editorOption"
                    v-if="editModeComputed"
                  />
                  <div v-html="editedItem.technical_information" v-else></div>
                </v-col>
              </v-row>

              <!-- Checklist Summary -->
              <v-row class="mb-10">
                <v-col cols="12" sm="12" md="3">
                  <v-subheader class="txt--text font-weight-black">
                    Checklist
                  </v-subheader>
                </v-col>
                <v-col cols="12" sm="12" md="9">
                  <v-text-field
                    v-model="checklist_summary"
                    solo
                    disabled
                    flat
                    max-height="100px"
                  ></v-text-field>
                </v-col>
              </v-row>

              <!-- Checklist -->
              <v-row v-for="checklist in checklists" :key="checklist.id">
                <v-col cols="12" sm="12" md="3">
                  <v-subheader class="txt--text font-weight-black">{{
                    checklist.title
                  }}</v-subheader>
                </v-col>
                <v-col
                  cols="12"
                  sm="12"
                  md="9"
                  class="d-flex flex-column justify-center"
                >
                  <!--  -->
                  <v-list
                    :outlined="editModeComputed"
                    :solo="!editModeComputed"
                    :disabled="!editModeComputed"
                    :flat="!editModeComputed"
                    input-value="true"
                  >
                    <v-list-item-group v-model="checklistsSelected" multiple>
                      <template>
                        <v-list-item
                          v-for="(item, i) in checklist.items"
                          :key="`item-${i}`"
                          :value="item.id"
                          active-class="secondary"
                          two-line
                        >
                          <template v-slot:default="{ active, toggle }">
                            <v-list-item-action>
                              <v-checkbox
                                :input-value="active"
                                :true-value="item.id"
                                :click="toggle"
                                on-icon="icon-selectionbox-checked"
                                off-icon="icon-selectionbox"
                              ></v-checkbox>
                            </v-list-item-action>

                            <v-list-item-content>
                              <v-list-item-title
                                v-text="item.title"
                              ></v-list-item-title>
                              <v-list-item-subtitle
                                v-if="item.subtitle"
                                v-text="item.subtitle"
                              ></v-list-item-subtitle>
                            </v-list-item-content>

                            <v-list-item-action>
                              {{ showChecklistInfo(item.id) }}
                            </v-list-item-action>
                          </template>
                        </v-list-item>
                      </template>
                    </v-list-item-group>
                  </v-list>
                  <!--  -->
                </v-col>
              </v-row>
            </v-container>
          </v-card-text>

          <v-divider />
          <v-card-actions v-if="editModeComputed">
            <v-btn
              class="ma-2 white--text"
              color="info"
              depressed
              rounded
              :disabled="loading"
              @click="validate"
              >{{ $t('general.save') }}</v-btn
            >
            <v-spacer />
            <v-btn
              class="ma-2 white--text"
              color="txt"
              depressed
              text
              :disabled="loading"
              @click="close"
              >{{ $t('general.cancel') }}</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-form>
    </v-dialog>

    <p v-if="isCreateMode" class="text-center">
      Bij het aanmaken van een nieuw product kiest u eerst voor 'Opslaan' om
      deze functie te activeren.
    </p>
  </accordion-card>
</template>

<script>
import Util from '@/util'
import accordionCard from '@/components/UI/AccordionCard/AccordionCard'
import universalFilterSelector from '@/components/UniversalFilterSelector/UniversalFilterSelector'

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

export default {
  components: {
    accordionCard,
    quillEditor,
    universalFilterSelector,
  },
  props: {
    editMode: {
      type: Boolean,
      default: false,
    },
    isCreateMode: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      options: {
        itemsPerPage: -1,
      },
      content: 'Write here your content...',
      editorOption: {
        modules: {
          toolbar: [
            [{ size: ['small', false, 'large'] }],
            ['bold', 'italic'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['link'],
          ],
        },
      },
      headers: [
        { text: 'versienummer', value: 'version_number' },
        { text: 'gemaakt door', value: 'made_by' },
        { text: 'ontwikkelomgeving', value: 'dev_environment' },
        { text: 'status', value: 'status' },
        { text: 'beschikbaar van', value: 'release_start' },
        { text: 'beschikbaar tot', value: 'release_end' },
        { text: '', value: 'actions' },
      ],
      rules: {
        version_number: [(v) => !!v || 'Het versienummer is verplicht.'],
        release_start: [
          (v) => !!v || 'De startdatum van de release is verplicht.',
        ],
      },
      valid: true,
      loading: false,
      date: null,
      menuPlanning: false,
      menuStart: false,
      menuEnd: false,
      modal: false,
      menu2: false,
      filterInputs: ['status', 'made_by', 'dev_environment', 'format_version'],
      version: {},
      versionEditMode: false,
      dialogVersion: false,
      dialogDelete: false,
      editedIndex: -1,
      editedItem: {
        version_number: '',
        release_start: '',
        release_end: '',
        release_planning_description: '',
        technical_information: '',
      },
      defaultItem: {
        version_number: '',
        release_start: '',
        release_end: '',
        release_planning_description: '',
        technical_information: '',
      },
      // startData: null,
    }
  },

  computed: {
    remote() {
      return this.$store.state.learning.remote
    },
    local() {
      return this.$store.state.learning.local
    },
    versions() {
      if (!this.local || !Array.isArray(this.local.versions)) return []
      return this.local.versions
    },
    versionsFiltersSelected() {
      return this.$store.state.learning.versionsFiltersSelected
    },
    hasVersions() {
      if (!this.versions) return false
      return this.versions.length > 0
    },

    hasTmpVersion() {
      return Util.isNotEmptyObj(this.version)
    },
    checklists() {
      return this.$store.state.learning.checklists || null
    },
    checklistsSelected: {
      get() {
        return this.$store.state.learning.checklistsSelected
      },
      set(value) {
        this.$store.commit('learning/SELECT_CHECKLIST', value)
      },
    },
    canEdit() {
      return (
        this.$route.query.edit === null &&
        (this.$store.getters.isAdmin || this.$store.getters.isOperator)
      )
    },

    formTitle() {
      return this.editedIndex === -1 ? 'Nieuwe versie' : 'Bewerken versie'
    },
    editModeComputed() {
      return this.versionEditMode && this.editMode
    },
    checklist_summary() {
      let totalChecklists = 0

      this.checklists.forEach((category) => {
        totalChecklists += category.items.length
      })

      return `${this.checklistsSelected.length} van ${totalChecklists} voltooid`
    },

    // computedDateFormattedStart() {
    //   return this.formatDate(this.editedItem.release_start)
    // },
    // computedDateFormattedEnd() {
    //   return this.formatDate(this.editedItem.release_end)
    // },

    computedDateFormattedStart: {
      get() {
        return this.formatDate(this.editedItem.release_start)
      },
      set(value) {
        this.editedItem.release_start = value
        // if (this.isValidDate(value)) {
        //   this.editedItem.release_start = value
        // }
      },
    },

      computedDateFormattedEnd: {
        get() {
          return this.formatDate(this.editedItem.release_end)
        },

        set(value) {
          this.editedItem.release_end = value
        },
      },
  },

  watch: {
    dialogVersion(val) {
      val || this.close()
    },
    // startData(val) {
    //   console.log(': val', val)
    //   if (this.isValidDate(val)) {
    //     this.editedItem.release_start = this.parseDate(val)
    //   }
    // },
  },

  methods: {
    validate() {
      if (!this.$refs.form.validate()) return
      this.save()
    },
    resetVersionsFilters() {
      this.versionEditMode = true
      this.$store.commit('learning/RESET_CHECKLIST_SELECTED')
      this.$store.commit('learning/RESET_VERSIONS_FILTERS')
    },

    formatDate(date) {
      if (!date) return null

      const [year, month, day, time] = date.replace(' ', '-').split('-')
      return `${day}/${month}/${year}`
    },

    parseDate(date) {
      if (!date || !this.isValidDate(date)) return null
      const [day, month, year] = date.split('/')
      if (day && day.length < 2) return null
      if (month && month.length < 2) return null
      if (year && year.length < 4) return null
      return `${year}-${month}-${day}`
    },

    isValidDate(date) {
      return new Date(date) !== 'Invalid Date' && !isNaN(new Date(date))
    },

    showChecklistInfo(checklistId) {
      if (
        !this.editedItem ||
        !this.editedItem.checklists ||
        !this.editedItem.checklists.length > 0
      )
        return null

      const checklistFound = this.editedItem.checklists.find(
        (checklist) => checklist.checklist_id === checklistId
      )
      if (!checklistFound) return null
      return `${checklistFound.created_at}, ${checklistFound.user.fullName}`
    },

    setVersionFiltersAndChecklist(item) {
      // Iterate item.filters and set in store versionsFiltersSelected filter_name: filter_item_id
      item.filters.forEach(async (f) => {
        const filterItem = this.$store.getters.getFilterItemById(
          f.filter_item_id
        )

        await this.$store.commit('learning/UPDATE_FILTERS', {
          filterId: filterItem.filter_id,
          target: 'versions',
          value: f.filter_item_id,
        })
      })

      const arrayChecklistIdsSelected = []

      item.checklists.forEach(async (checklist) => {
        arrayChecklistIdsSelected.push(checklist.checklist_id)
        this.$store.commit(
          'learning/SET_CHECKED_CHECKLISTS',
          arrayChecklistIdsSelected
        )
      })

      this.editedIndex = this.versions.indexOf(item)
      this.editedItem = Object.assign({}, item)
      this.$forceUpdate()
    },

    getFilterItem(filterTitle, version) {
      const filter = this.$store.getters.getFilterByTitle(filterTitle)

      const arrayTmp = []
      if (!version.filters) return {}
      version.filters.forEach((f) => {
        const filterItemTmp = this.$store.getters.getFilterItemById(
          f.filter_item_id
        )
        arrayTmp.push(filterItemTmp)
      })

      const filterItem = arrayTmp.find((e) => e.filter_id === filter.id)
      return filterItem || {}
    },

    viewItem(item) {
      this.versionEditMode = false
      this.setVersionFiltersAndChecklist(item)
      this.dialogVersion = true
    },

    editItem(item) {
      if (!this.editMode) return
      this.versionEditMode = true
      this.setVersionFiltersAndChecklist(item)
      this.dialogVersion = true
      // this.$refs.input.focus()
    },

    async deleteItem(item) {
      this.$nextTick(() => this.$nuxt.$loading.start())
      if (!item.id) {
        this.$notifier.showMessage({
          content: `No version to delete selected`,
          color: 'error',
          icon: 'icon-message',
        })
      }

      try {
        const response = await this.$axios.delete(`/versions/${item.id}`)

        this.$store.commit('learning/DELETE_VERSION_LOCAL', item)

        this.dialogDelete = false
        this.dialogVersion = false
        this.$nuxt.$loading.finish()

        this.$notifier.showMessage({
          content: `Version deleted`,
          color: 'success',
          icon: 'mdi-delete',
        })
      } catch (error) {
        this.$nuxt.$loading.finish()
        this.$notifier.showMessage({
          content: `Error trying to delete the selected version`,
          color: 'error',
          icon: 'mdi-delete',
        })
      }
    },

    close() {
      this.dialogVersion = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
        this.$refs.card.$el.scrollIntoView(true)
      })
    },

    setFiltersSelectedInEditedItem() {
      let versionFiltersItemsIds = []

      for (const [key, value] of Object.entries(this.versionsFiltersSelected)) {
        versionFiltersItemsIds.push(value)
      }

      this.editedItem['filter_items'] = versionFiltersItemsIds
    },

    setChecklistsSelectedInEditedItem() {
      this.editedItem['checklists_selected'] = [
        ...this.$store.state.learning.checklistsSelected,
      ]
    },

    async save() {
      this.$nextTick(() => {
        this.$refs.card.$el.scrollIntoView(true)
      })
      this.loading = true
      this.$nextTick(() => this.$nuxt.$loading.start())

      // Edit mode
      if (this.editedIndex > -1) {
        try {
          this.editedItem.learning_product_id = this.local.id

          this.setFiltersSelectedInEditedItem()
          this.setChecklistsSelectedInEditedItem()

          const response = await this.$axios.post('/versions', this.editedItem)

          this.$store.commit('learning/EDIT_VERSION_LOCAL', {
            index: this.editedIndex,
            version: response.data,
          })

          this.dialogVersion = false

          this.$notifier.showMessage({
            content: `Version stored`,
            color: 'success',
            icon: 'icon-checkmark',
          })
        } catch (error) {
          console.log('save -> error', error)

          this.dialogVersion = false

          this.$nuxt.$loading.finish()

          this.$notifier.showMessage({
            content: `Error trying to store the version`,
            color: 'error',
            icon: 'mdi-delete',
          })
        }
        // Create new mode
      } else {
        try {
          this.editedItem.learning_product_id = this.local.id

          this.setFiltersSelectedInEditedItem()
          this.setChecklistsSelectedInEditedItem()

          const response = await this.$axios.post('/versions', this.editedItem)

          this.dialog = false

          this.$store.commit('learning/ADD_VERSION_LOCAL', response.data)

          this.$notifier.showMessage({
            content: `Version stored`,
            color: 'success',
            icon: 'icon-checkmark',
          })
        } catch (error) {
          console.log('save -> error', error)

          this.dialogVersion = false

          this.$nuxt.$loading.finish()

          this.$notifier.showMessage({
            content: `Error trying to store the version`,
            color: 'error',
            icon: 'mdi-delete',
          })
        }
      }

      this.$nuxt.$loading.finish()
      this.loading = false
      this.close()
    },
  },
}
</script>

<style scoped>
.v-card >>> table,
.v-card >>> .v-data-table-header tr,
.v-card >>> .v-data-footer {
  background-color: var(--v-primary-base);
}
.v-card >>> .v-data-table-header th span {
  color: var(--v-tertiary-base);
}
.v-card >>> .text-start,
.v-card >>> .v-icon,
.v-dialog__content >>> .v-subheader,
.v-dialog__content >>> i {
  color: var(--v-txt-base);
  font-weight: bold;
}

.v-card >>> p {
  margin: 0;
  color: var(--v-txt-base);
}

.v-dialog .v-card {
  background: var(--v-secondary-base);
}

table tr button.view {
  opacity: 0;
}
table tr:hover button.view {
  opacity: 1;
}
.v-dialog__content >>> .v-dialog {
  border: 4px solid var(--v-secAccent-base);
  max-height: 68%;
  /* box-shadow: inset 0px 0px 2px 2px var(--v-secAccent-base),
    inset 6px 6px 14px -14px var(--v-secAccent-base) !important; */
}

.v-dialog__content >>> .v-input__slot {
  background: var(--v-primary-base);
  border: 1px solid var(--v-lines-base);
}

.v-list-item >>> .v-input__slot {
  background: unset;
  border: none;
}
.v-list-item--active.secondary {
  background-color: var(--v-primary-base) !important;
}
.v-list-item--active::before {
  background-color: unset;
}

.v-list {
  padding: 0;
}
.v-menu__content >>> .v-date-picker-table {
  height: 242px !important;
}
</style>
