<template>
  <accordion-card title="Contributie">
    <v-data-table
      :headers="headers"
      :items="contributions"
      :options="options"
      sort-by="year"
      sort-desc
      hide-default-footer
      item-key="accreditation"
      flat
      v-if="hasContributions"
    >
     <template v-slot:item.contribution="{ item }">€ {{new Intl.NumberFormat().format(item.contribution)}},00</template>
      <template v-slot:item.profiel="{ item }">
        <v-icon
          :color="!item.approved_at ? 'accent' : 'success'"
          >{{
            !item.approved_at
              ? 'mdi-alert-circle-outline'
              : 'icon-checkmark'
          }}</v-icon
        >
      </template>

      <template v-slot:item.actions="{ item }">
        <v-menu
          offset-y
          v-if="editMode && $store.getters.isSuperAdminOrAdmin"
        >
          <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="editMode"
              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.delete_contributionmembers_confirmation') }}
                </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="dialogContribution"
      max-width="75%"
      v-if="editMode && $store.getters.isSuperAdminOrAdmin"
    >
      <template v-slot:activator="{ on, attrs }">
        <v-btn
          v-if="editMode && ($store.getters.isSuperAdmin || $store.getters.isAdmin)"
          class="my-10 cta-secondary"
          block
          depressed
          min-height="60px"
          :disabled="isCreateMode"
          v-on="on"
        >
          <v-icon x-small class="mx-4">icon-add</v-icon>

          Voeg jaartal toe</v-btn
        >
      </template>
      <v-card ref="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="6">
                <v-subheader class="txt--text font-weight-black"
                  >Jaar</v-subheader
                >
              </v-col>
              <v-col cols="12" sm="12" md="6">
                <v-select
                  :items="yearsComputed"
                  v-model="editedItem.year"
                  :outlined="editMode"
                  :solo="!editMode"
                  :disabled="!editMode || !$store.getters.isSuperAdminOrAdmin"
                  :flat="!editMode"
                  v-if="isCreatedModeContribution"
                />
                <v-text-field
                  v-model="editedItem.year"
                  :outlined="editMode"
                  :solo="!editMode"
                  disabled
                  :flat="!editMode"
                  v-else
                />
              </v-col>
            </v-row>

            <v-row>
              <v-col cols="12" sm="12" md="6">
                <v-subheader class="txt--text font-weight-black"
                  >Contributie
                </v-subheader>
              </v-col>
              <v-col cols="12" sm="12" md="6">
                <v-text-field
                  v-model="editedItem.contribution"
                  :outlined="editMode"
                  :solo="!editMode"
                  :disabled="!editMode"
                  :flat="!editMode"
                  type="number"
                  prepend-inner-icon="mdi-currency-eur"
                ></v-text-field>
              </v-col>
            </v-row>

            <v-row v-if="isCreatedModeContribution && editMode && $store.getters.isSuperAdminOrAdmin">
              <v-col cols="12" sm="12" md="6">
                <v-subheader class="txt--text font-weight-black"
                  >Pas toe op alle leden
                </v-subheader>
              </v-col>
              <v-col class="checkbox" cols="12" sm="12" md="1">
                <v-checkbox
                  v-model="editedItem.toAll"
                  :disabled="!editMode"
                ></v-checkbox>
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>

        <v-divider />
        <v-card-actions v-if="editMode">
          <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 lid kiest u eerst voor 'Tussentijds
      Opslaan' om deze functie te activeren.
    </p>
  </accordion-card>
</template>

<script>
import accordionCard from '@/components/UI/AccordionCard/AccordionCard'
export default {
  components: {
    accordionCard,
  },
  props: {
    editMode: {
      type: Boolean,
      default: false,
    },
    isCreateMode: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      options: {
        itemsPerPage: -1,
      },
      headers: [
        { text: 'jaar', value: 'year' },
        { text: 'contributie' , value: 'contribution' },
        { text: 'profiel', value: 'profiel', sortable: false },
        { text: '', value: 'actions' },
      ],
      dialogContribution: false,
      dialogDelete: false,
      editedIndex: -1,
      editedItem: {},
      defaultItem: {},
      loading: false,
    }
  },
  computed: {
    local() {
      return this.$store.state.members.local
    },

    isCreatedModeContribution() {
      return this.editedIndex === -1
    },

    formTitle() {
      return this.isCreatedModeContribution ? 'Nieuw' : 'Bewerk'
    },

    contributions() {
      if (!this.local || !Array.isArray(this.local.contributions)) return []
      return this.local.contributions
    },
    hasContributions() {
      if (!this.contributions) return false
      return this.contributions.length > 0
    },

    years() {
      const year = new Date().getFullYear()
      return Array.from({ length: 51 }, (value, index) => 2010 + index)
    },

    yearsTaken() {
      if (!this.hasContributions) return []
      return this.contributions.map(({ year }) => year)
    },

    yearsComputed() {
      return this.years.filter((y) => !this.yearsTaken.includes(y))
    },
  },

  watch: {
    dialogContribution(val) {
      val || this.close()
    },
  },

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

    editItem(item) {
      if (!this.editMode) return
      this.setSummaryToEdit(item)
      this.dialogContribution = true
    },

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

    close() {
      this.dialogContribution = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

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

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

      try {
        await this.$store.dispatch('members/deleteContribution', item)

        this.dialogDelete = false
        this.dialogContribution = false
        this.$nuxt.$loading.finish()
      } catch (error) {
        console.log('deleteItem -> error', error)
        this.$nuxt.$loading.finish()
      }

      this.$forceUpdate()
    },

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

      if (this.isCreatedModeContribution) {
        try {
          await this.$store.dispatch(
            'members/storeContribution',
            this.editedItem
          )
          this.loading = false
        } catch (error) {
          console.log('save -> error', error)
          this.loading = false
        }
      } else {
        // Edit mode
        try {
          await this.$store.dispatch(
            'members/storeContribution',
            this.editedItem
          )
          this.dialogContribution = false
          this.loading = false
        } catch (error) {
          console.log('save -> error', error)
          this.loading = false
        }
      }

      this.close()
      this.$nuxt.$loading.finish()
    },
  },
}
</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 >>> .v-subheader {
  padding: 0px !important;
}
.v-dialog__content >>> .v-dialog {
  border: 4px solid var(--v-secAccent-base);
  /* 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);
}
.v-menu__content >>> .v-date-picker-table {
  height: 285px !important;
}
</style>
