<template>
  <accordion-card :title="$t('learning.product_overview.notifications')">
    <v-data-table
      :headers="headers"
      :items="notifications"
      :options="options"
      hide-default-footer
      item-key="notification"
      flat
      v-if="hasNotifications"
    >
      <template v-slot:item.date="{ item }">{{
        formatDate(item.date)
      }}</template>

      <template v-slot:item.sent="{ item }">
        <v-icon color="teal" class="icon-checkmark" v-if="item.sent"></v-icon>
        <v-icon color="red" class="icon-close" size="8" v-else></v-icon>
      </template>

      <template v-slot:item.actions="{ item }">
        <v-btn
          class="mx-4 white--text button-hover"
          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.subject,
                    })
                  }}
                </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="dialogNotification"
      max-width="75%"
      v-if="$store.getters.isAdmin || $store.getters.isOperator"
    >
      <template v-slot:activator="{ on, attrs }">
        <v-btn
          v-if="editMode"
          class="my-10 cta-secondary"
          block
          depressed
          min-height="60px"
          :disabled="isCreateMode"
          v-on="on"
          @click="notificationEditMode = true"
        >
          <v-icon x-small class="mx-4">icon-add</v-icon>
          {{ $t('learning.add_new_notification') }}
        </v-btn>
      </template>
      <v-card>
        <v-card-title>
          <span class="headline">{{ formTitle }}</span>
        </v-card-title>

        <v-card-text>
          <v-container>
            <v-row>
              <v-col cols="12" sm="12" md="2">
                <v-subheader class="txt--text font-weight-black">{{
                  $t('learning.actions.date_time')
                }}</v-subheader>
              </v-col>
              <v-col cols="12" sm="12" md="8" class="d-flex">
                <v-menu
                  ref="menuDate"
                  v-model="menuDate"
                  :close-on-content-click="false"
                  transition="scale-transition"
                  offset-y
                  min-width="290px"
                >
                  <template v-slot:activator="{ on, attrs }">
                    <v-text-field
                      :name="`notification-date-${Math.random()}`"
                      v-model="computedDateFormatted"
                      max-height="100px"
                      v-bind="attrs"
                      v-on="on"
                      :outlined="editModeComputed"
                      :solo="!editModeComputed"
                      :disabled="!editModeComputed"
                      :flat="!editModeComputed"
                      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.date"
                    no-title
                    scrollable
                    :disabled="!editModeComputed"
                    :flat="!editModeComputed"
                    locale="nl-NL"
                  >
                    <v-spacer></v-spacer>
                    <v-btn text @click="menuDate = false">Cancel</v-btn>
                    <v-btn text @click="$refs.menuDate.save(editedItem.date)"
                      >OK</v-btn
                    >
                  </v-date-picker>
                </v-menu>
                <span class="mx-5 my-3 font-weight-bold">{{
                  $t('learning.actions.at')
                }}</span>
                <v-menu
                  ref="menuTime"
                  v-model="menuTime"
                  :close-on-content-click="false"
                  :nudge-right="40"
                  :return-value.sync="editedItem.time"
                  transition="scale-transition"
                  offset-y
                  max-width="290px"
                  min-width="290px"
                >
                  <template v-slot:activator="{ on, attrs }">
                    <v-text-field
                      :name="`notification-time-${Math.random()}`"
                      v-model="editedItem.time"
                      :outlined="editModeComputed"
                      :solo="!editModeComputed"
                      :disabled="!editModeComputed"
                      :flat="!editModeComputed"
                      readonly
                      v-bind="attrs"
                      v-on="on"
                    ></v-text-field>
                  </template>

                  <v-time-picker
                    v-if="menuTime"
                    v-model="editedItem.time"
                    full-width
                    format="24hr"
                    @click:minute="$refs.menuTime.save(editedItem.time)"
                  ></v-time-picker>
                </v-menu>
              </v-col>
              <v-col cols="12" sm="12" md="2">
                <v-subheader class="txt--text font-weight-black"></v-subheader>
              </v-col>
            </v-row>

            <v-row>
              <v-col cols="12" sm="12" md="2">
                <v-subheader class="txt--text font-weight-black">{{
                  $t('learning.actions.mail_addresses')
                }}</v-subheader>
              </v-col>
              <v-col cols="12" sm="12" md="8" class="d-flex">
                <v-combobox
                  v-model="editedItem.emails"
                  hide-selected
                  label="Add emails here"
                  multiple
                  chips
                  solo
                  :disabled="!editModeComputed"
                >
                  <template
                    v-slot:selection="{ attrs, item, parent, selected }"
                  >
                    <v-chip
                      v-bind="attrs"
                      :input-value="selected"
                      small
                      :close="editModeComputed"
                      @click:close="parent.selectItem(item)"
                    >
                      <span class="pr-2">{{ item }}</span>
                    </v-chip>
                  </template>
                </v-combobox>
              </v-col>
              <v-col cols="12" sm="12" md="2">
                <v-subheader class="txt--text font-weight-black"></v-subheader>
              </v-col>
            </v-row>

            <v-row>
              <v-col cols="12" sm="12" md="2">
                <v-subheader class="txt--text font-weight-black">{{
                  $t('learning.actions.users')
                }}</v-subheader>
              </v-col>
              <v-col cols="12" sm="12" md="8" class="d-flex users">
                <v-autocomplete
                  v-model="editedItem.users"
                  :items="users"
                  chips
                  color="blue-grey lighten-2"
                  item-text="fullName"
                  item-value="id"
                  multiple
                  hide-selected
                  :outlined="editModeComputed"
                  :solo="!editModeComputed"
                  :disabled="!editModeComputed"
                  :flat="!editModeComputed"
                >
                  <template v-slot:selection="data">
                    <v-chip
                      v-bind="data.attrs"
                      :input-value="data.id"
                      :close="editModeComputed"
                      @click="data.select"
                      @click:close="removeUser(data.item.id)"
                      >{{ data.item.fullName }}</v-chip
                    >
                  </template>
                  <template v-slot:item="data">
                    <template>
                      <v-list-item-content>
                        <v-list-item-title
                          v-html="data.item.fullName"
                        ></v-list-item-title>
                        <!-- <v-list-item-subtitle
                          v-html="data.item.group"
                        ></v-list-item-subtitle>-->
                      </v-list-item-content>
                    </template>
                  </template>
                </v-autocomplete>
              </v-col>

              <v-col cols="12" sm="12" md="2"></v-col>
            </v-row>

            <v-row>
              <v-col cols="12" sm="12" md="2">
                <v-subheader class="txt--text font-weight-black">{{
                  $t('learning.actions.subject')
                }}</v-subheader>
              </v-col>
              <v-col cols="12" sm="12" md="8" class="d-flex">
                <v-text-field
                  v-model="editedItem.subject"
                  :outlined="editModeComputed"
                  :solo="!editModeComputed"
                  :disabled="!editModeComputed"
                  :flat="!editModeComputed"
                ></v-text-field>
              </v-col>
              <v-col cols="12" sm="12" md="2">
                <v-subheader class="txt--text font-weight-black"></v-subheader>
              </v-col>
            </v-row>

            <v-row>
              <v-col cols="12" sm="12" md="2">
                <v-subheader class="txt--text font-weight-black">{{
                  $t('learning.actions.message')
                }}</v-subheader>
              </v-col>
              <v-col cols="12" sm="12" md="8">
                <quill-editor
                  class="quill primary"
                  :options="editorOption"
                  v-model="editedItem.message"
                  style="width: 100%"
                  v-if="editModeComputed"
                />
                <span v-html="editedItem.message" v-else></span>
              </v-col>
              <v-col cols="12" sm="12" md="2">
                <v-subheader class="txt--text font-weight-black"></v-subheader>
              </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="save"
            >{{ $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-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>

    <v-row>
      <v-col cols="12" sm="12" md="3">
        <v-subheader class="txt--text font-weight-black in_the_picture"
          >In the picture</v-subheader
        >
      </v-col>
      <v-col cols="12" sm="12" md="9" class="mb-4 d-flex flex-column">
        <div class="pb-0 mb-0 d-flex">
          <v-switch
            :disabled="!editMode"
            inset
            class="toggle my-3"
            v-model="in_the_picture"
          />

          <v-text-field
            :value="computedInThePicDateFormattedStart"
            readonly
            prepend-inner-icon="icon-events"
            :outlined="editMode"
            :solo="!editMode"
            :flat="!editMode"
          />
          <span class="mx-5 my-3 font-weight-bold"> tot </span>
          <v-text-field
            :value="computedInThePicDateFormattedEnd"
            readonly
            :outlined="editMode"
            :solo="!editMode"
            :flat="!editMode"
            append-icon="icon-events"
          />
        </div>
        <v-date-picker
          v-if="$store.getters.isSuperAdminOrAdmin"
          v-model="dates"
          no-title
          :disabled="!editMode"
          flat
          first-day-of-week="1"
          range
          full-width
          locale="nl-NL"
        />
      </v-col>
    </v-row>
  </accordion-card>
</template>

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

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,
  },
  props: {
    editMode: {
      type: Boolean,
      default: false,
    },
    isCreateMode: {
      type: Boolean,
      default: true,
    },
    users: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      picker: new Date(Date.now() - new Date().getTimezoneOffset() * 60000)
        .toISOString()
        .substr(0, 10),

      options: {
        itemsPerPage: -1,
      },
      headers: [
        { text: 'subject', value: 'subject' },
        { text: 'date', value: 'date' },
        { text: 'time', value: 'time' },
        { text: 'sent', value: 'sent' },
        { text: '', value: 'actions' },
      ],
      loading: false,
      dialogNotification: false,
      dialogDelete: false,

      editedIndex: -1,
      editedItem: {
        date: '',
        time: null,
        emails: [],
        users: [],
        subject: '',
        message: '',
      },
      defaultItem: {
        date: '',
        time: null,
        emails: [],
        users: [],
        subject: '',
        message: '',
      },
      content: 'Write here your content...',
      editorOption: {
        modules: {
          toolbar: [
            [{ size: ['small', false, 'large'] }],
            ['bold', 'italic'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['link'],
          ],
        },
      },
      notificationEditMode: false,
      autoUpdate: true,
      isUpdating: false,
      activator: null,
      attach: null,
      editing: null,
      index: -1,
      date: null,
      menu: false,
      menuStart: false,
      menuEnd: false,
      menuDate: false,
      menuTime: false,
      menu2: false,
      x: 0,
      y: 0,
      dates: [],
    }
  },

  watch: {
    dialogNotification(val) {
      val || this.close()
    },
    dates(val) {
      // If the second date is earlier than the first, switch them
      if (val.length === 2 && val[1] < val[0]) this.dates.reverse()

      this.$store.commit('learning/UPDATE_FIELD', {
        field: 'in_the_picture_start',
        value: val[0] || null,
      })
      this.$store.commit('learning/UPDATE_FIELD', {
        field: 'in_the_picture_end',
        value: val[1] || null,
      })
    },
  },

  computed: {
    local() {
      return this.$store.getters.localProduct
    },
    notifications() {
      if (!this.local || !Array.isArray(this.local.notifications)) return []
      return this.local.notifications
    },
    hasNotifications() {
      return this.notifications.length > 0
    },
    formTitle() {
      return this.editedIndex === -1
        ? 'Nieuwe notificatie'
        : 'Bewerken notificatie'
    },
    editModeComputed() {
      return this.notificationEditMode && this.editMode
    },
    computedDateFormatted() {
      return this.formatDate(this.editedItem.date)
    },
    computedInThePicDateFormattedStart() {
      return this.formatDate(this.in_the_picture_start)
    },
    computedInThePicDateFormattedEnd() {
      return this.formatDate(this.in_the_picture_end)
    },
    in_the_picture: {
      get() {
        return this.local.in_the_picture
      },
      set(value) {
        this.$store.commit('learning/UPDATE_FIELD', {
          field: 'in_the_picture',
          value,
        })
      },
    },

    in_the_picture_start() {
      return this.local.in_the_picture_start
    },
    in_the_picture_end() {
      return this.local.in_the_picture_end
    },
  },

  methods: {
    assignItemToEdited(item) {
      this.editedIndex = this.notifications.indexOf(item)
      this.editedItem = Object.assign({}, item)

      if (typeof this.editedItem.users === 'string') {
        this.editedItem.users = JSON.parse(this.editedItem.users)
      }
      if (typeof this.editedItem.emails === 'string') {
        this.editedItem.emails = JSON.parse(this.editedItem.emails)
      }
    },
    formatDate(date) {
      if (!date) return null

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

    viewItem(item) {
      this.editedIndex = this.notifications.indexOf(item)
      this.notificationEditMode = false
      this.assignItemToEdited(item)
      this.dialogNotification = true
    },

    editItem(item) {
      if (!this.editMode) return
      this.notificationEditMode = true
      this.assignItemToEdited(item)
      this.dialogNotification = true
    },

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

      try {
        const response = await this.$axios.delete(
          `/learning-products/notifications/${item.id}`
        )

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

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

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

    async save() {
      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.editedItem.sent = 0

          const response = await this.$axios.post(
            '/learning-products/notifications',
            this.editedItem
          )

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

          this.dialogAccreditation = false

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

          this.dialogNotification = false

          this.$nuxt.$loading.finish()

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

          let data = { ...this.editedItem }
          data['emails'] = JSON.stringify(data['emails'])
          data['users'] = JSON.stringify(data['users'])

          const response = await this.$axios.post(
            '/learning-products/notifications',
            data
          )

          this.dialog = false

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

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

          this.dialogAccreditation = false

          this.$nuxt.$loading.finish()

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

      this.$nuxt.$loading.finish()
      this.loading = false
      this.close()
    },
    close() {
      this.dialogNotification = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },
    edit(index, item) {
      if (!this.editing) {
        this.editing = item
        this.index = index
      } else {
        this.editing = null
        this.index = -1
      }
    },

    removeUser(userId) {
      const index = this.editedItem.users.indexOf(userId)

      if (index >= 0) {
        let arrayUsers = [...this.editedItem.users]
        arrayUsers.splice(index, 1)
        this.editedItem.users = [...arrayUsers]
      }
    },
  },
}
</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,
.font-weight-bold {
  color: var(--v-txt-base);
  font-weight: bold;
}
.v-card >>> .in_the_picture {
  padding-left: 4px;
}
.v-dialog__content >>> .v-dialog {
  border: 4px solid var(--v-secAccent-base);
  max-height: 68% !important;

  /* box-shadow: inset 0px 0px 2px 2px var(--v-secAccent-base),
    inset 6px 6px 14px -14px var(--v-secAccent-base) !important; */
}
.v-dialog .v-card {
  background: var(--v-secondary-base);
}

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

table tr .button-hover.v-btn {
  opacity: 0;
}
table tr:hover .button-hover.v-btn {
  opacity: 1;
}
.v-autocomplete__content {
  top: 532px !important;
  left: 507px !important;
}

.v-autocomplete__content >>> .v-list .v-list-item:first-child {
  pointer-events: auto !important;
  cursor: pointer !important;
}
.v-autocomplete__content
  .v-list
  .v-list-item:first-child
  .v-list-item__content {
  border-bottom: 0px solid var(--v-search-base) !important;
  padding-bottom: unset !important;
}
.v-autocomplete__content .v-list {
  padding: 6px !important;
}
.v-autocomplete__content .v-list .v-list-item:first-child .v-list-item__title {
  font-weight: 400 !important;
}
.v-text-field.v-text-field--solo >>> .v-input__append-inner {
  align-self: baseline;
}
.v-text-field.v-text-field--solo >>> .v-input__slot {
  padding: 8px 12px !important;
}
.v-text-field.v-text-field--solo >>> .v-input__icon--append {
  margin-top: 8px;
}
</style>
