<template>
  <div class="container mt-2">
    <div class="row m-0" v-if="!cockpitDoneBtn">
      <div class="col-12">
        <div class="form-group">
          <label for class="label text-common-style mb-0">Add Email</label>
          <multiselect
            v-model="emailTag"
            tag-placeholder="Add this as new tag"
            placeholder="Search or add a email"
            label="email"
            track-by="email"
            :options="emailOptions"
            :multiple="true"
            :taggable="true"
            @tag="addTag"
          ></multiselect>
        </div>
      </div>
    </div>
    <div class="row m-0 mb-3" v-if="!cockpitDoneBtn">
      <div class="col-12 manage-access" @click="manageAccess()">
        <span>
        <svg class="icon-square">
          <use xlink:href="/assets/img/mads-common-icons.svg#gear" />
        </svg>
      </span>
      <span>
        Manage Access
      </span>
      </div>
    </div>
    <div class="row m-0" v-if="toggleTextArea && !cockpitDoneBtn">
      <div class="col-12">
        <div class="form-group">
          <!-- <textarea class="form-control email-textarea" v-model="textareaMessage"></textarea> -->
          <vue-editor v-model="textareaMessage"></vue-editor>
        </div>
      </div>
    </div>
    <div class="row m-0" v-if="cockpitDoneBtn">
      <div class="col-12">
        <div class="form-group">
          <input type="text" v-model="search" placeholder="Search people" class="form-control search-input">
        </div>
        <div>
        <div class="shared-with">Shared with</div>
        <div class="shared-users">
          <div class="items d-flex align-items-center justify-content-between mb-2" v-for="(email) in filteredList" :key="email.email">
          <div class="d-flex justify-content-between align-items-center">
            <div class="first-char d-flex justify-content-center align-items-center" :style="{backgroundColor: randomBgColor()}">{{email.email.charAt(0).toUpperCase() }}</div>
            <div class="ml-3">{{email.email}}</div>
          </div>
          <div><button class="btn btn-outline-danger remove-btn" @click="cockpitRevokeUser(email.email)">Remove</button></div>
        </div>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script>
import { VueEditor } from 'vue2-editor'
export default {
  props: ['selectedDashboard', 'currentUser', 'cockpitDoneBtn', 'dashboardService'],
  components: {
    VueEditor
  },
  data () {
    return {
      emailTag: [],
      emailOptions: [],
      textareaMessage: null,
      getUsers: [],
      allUsers: [],
      search: ''
    }
  },
  methods: {
    addTag (newTag) {
      const tag = { 'email': newTag, 'first_name': null, 'last_name': null }
      this.emailOptions.push(tag)
      this.emailTag.push(tag)
    },
    setTextAreaMessage () {
      const creator = this.selectedDashboard.creator.first_name +
        ' ' +
        this.selectedDashboard.creator.last_name
      // const textAreaContent =
      //   'Hello!' +
      //   creator +
      //   ' from Datakrew organization would like to share with you ' +
      //   this.selectedDashboard.name +
      //   ' You can access this dashboard by logging in at cockpit.mads-iot.com'
      // this.textareaMessage = textAreaContent
      const testMessage = `Hello!<span><strong>${creator}</strong> from Datakrew organization would like to share with you <strong>${this.selectedDashboard.name}</strong> You can access this dashboard by logging in at <a href="cockpit.mads-iot.com">cockpit.mads-iot.com</a></span>`
      this.textareaMessage = testMessage
    },
    removeEmail (index) {
      this.emailTag.splice(index, 1)
    },
    manageAccess () {
      this.$emit('manage-access')
    },
    onShare () {
      let emails = this.emailTag.map(({ email }) => email)
      let config = { orgId: this.currentUser.org.id, dashboardId: this.selectedDashboard.id }
      let data = { 'share_with': emails }
      this.dashboardService.shareViaCockpit(config, data)
        .then((res) => {
          this.$toastr.success(res.status)
          this.$emit('close-modal')
        })
        .catch((err) => {
          this.$toastr.error(err.title)
        })
    },
    getSharedUsers () {
      let config = { orgId: this.currentUser.org.id, dashboardId: this.selectedDashboard.id }
      this.dashboardService.cockpitSharedUsers(config)
        .then((res) => {
          this.getUsers = res.users
        })
        .catch((err) => {
          this.$toastr.error(err.title)
        })
    },
    cockpitRevokeUser (email) {
      let config = { orgId: this.currentUser.org.id, dashboardId: this.selectedDashboard.id, userEmail: email }
      this.dashboardService.cockpitRevokeUser(config)
        .then((res) => {
          this.getSharedUsers()
          this.$toastr.success(res.status)
        })
        .catch((err) => {
          this.$toastr.error(err.title)
        })
    },
    randomBgColor () {
      return '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
    }
  },
  mounted () {
    this.getSharedUsers()
  },
  computed: {
    toggleTextArea () {
      if (this.emailTag.length > 0) {
        this.setTextAreaMessage()
        this.$emit('share-btn-toggle', true)
        return true
      } else {
        this.$emit('share-btn-toggle', false)
        return false
      }
    },
    filteredList () {
      return this.getUsers.filter(post => {
        return this.search ? post.email.toLowerCase().includes(this.search.toLowerCase()) : this.getUsers
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.email-textarea {
    height: 130px;
    background: #ffffff;
    border: 1px solid #acb5bd;
    box-sizing: border-box;
    border-radius: 6px;
}
.first-char {
  min-height: 40px;
  min-width: 40px;
  background-color: #44d8bd;
  display: inline-block;
  border-radius: 50%;
  color: #FFF;
  font-weight: 400;
}
.remove-btn {
  border-radius: 8px;
}
.shared-with {
  color: rgba(33, 36, 41, 0.5);
  font-size: 12px;
  font-weight: 600;
}
.search-input {
  border: 1px solid #ACB5BD;
  border-radius: 8px;
  height: 51px;
  background: url(../icon/search.svg) no-repeat 15px 50%;
  padding-left: 45px;
}
.manage-access {
  color: #0D85DA;
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}
.icon-square {
  height: 20px;
  width: 20px;
}
.shared-users {
  max-height: 230px;
  overflow-x: hidden;
  overflow-y: scroll;
}
</style>
