<template>
  <b-dropdown
    right
    class="text-capitalize"
    variant="outline-primary"
    :text="$t('MyBundle.Details.Dropdown.Actions')"
    :data-qa="`${dataQaPrefix}-actions-dropdown`"
  >
    <b-dropdown-item
      :to="{ name: 'MyBundleSelectProduct', params: { page: 1 }, query: { id: bundleId } }"
      :data-qa="`${dataQaPrefix}-edit-action-dropdown-item`"
    >
      <span>{{ $t('MyBundle.Details.Button.EditBundle') }}</span>
    </b-dropdown-item>
    <b-dropdown-divider></b-dropdown-divider>

    <b-dropdown-item @click="$emit('viewAnalytic')" :data-qa="`${dataQaPrefix}-view-analytic-dropdown-item`">
      <span>{{ $t('MyBundle.BundleAnalytic.ViewAnalytic') }}</span>
    </b-dropdown-item>
    <b-dropdown-divider></b-dropdown-divider>

    <b-dropdown-item class="text-danger" @click="deleteBundle" :data-qa="`${dataQaPrefix}-remove-action-dropdown-item`">
      <span class="text-danger">{{ $t('MyBundle.Details.Button.RemoveBundle') }}</span>
    </b-dropdown-item>
  </b-dropdown>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'BundleDetailsActionsDropdown',
  props: {
    bundleId: { type: Number, required: true },
    dataQaPrefix: { type: String, required: true },
  },
  methods: {
    ...mapActions('myBundle', ['removeBundle']),
    async deleteBundle() {
      let self = this
      await this.$swal({
        type: 'warning',
        title: this.$t('MyBundle.Details.RemovePopUp.title'),
        text: this.$t('MyBundle.Details.RemovePopUp.text'),
        reverseButtons: true,
        showCancelButton: true,
        allowOutsideClick: false,
        showLoaderOnConfirm: true,
        confirmButtonClass: 'bg-danger',
        confirmButtonText: this.$t('MyBundle.Details.RemovePopUp.Action.Remove'),
        cancelButtonText: this.$t('Common.Cancel'),
        preConfirm: async () => {
          let result = await self.removeBundle(this.bundleId)
          return { response: result }
        },
      }).then(result => {
        let title =
          result.value && result.value.response
            ? 'MyBundle.Details.RemovePopUp.Remove.Success.title'
            : 'MyBundle.Details.RemovePopUp.Remove.Fail.title'

        this.$swal({
          title: this.$t(title),
          text: result.value.response ? '' : this.$t('Common.Error.ActionFailure.HelpText'),
          type: (result.value.response && 'success') || 'error',
          timer: result.value.response && '2500',
        })

        if (result.value.response) {
          this.$router.push({ name: 'MyBundle' })
        }
      })
    },
  },
}
</script>
