<template>
  <div>

    <ion-item v-if="newDay" lines="none" class="loc-item new-day">
      <div style="width: 100%">{{ newDay }}</div>
    </ion-item>

    <ion-item 
      v-if="message.type === 'forum_post' || (!isGroupped && message.type !== 'introduction' && !isMine)" 
      lines="none" 
      class="loc-item user"
      @click.stop="!message.user.isDeleted ? $emit('introductionClicked', message) : null"
    >
      <ion-avatar slot="start" class="loc-avatar">
        <img v-if="message.type === 'forum_post' || (!isMine && !isGroupped)" :src="message.user.avatar" />
      </ion-avatar>
      <span class="sender-name">{{ message.user.name }} <div v-if="message.user.isDeleted" class="user-left-flag">~left the conversation</div></span>
    </ion-item>

    <ion-item 
      v-if="isSenderParticipant || isMeOwner"
      lines="none" class="loc-item" 
      :dynClass="isMine && message.type !== 'forum_post' ? 'is-mine' : 'is-not-mine'"
    >
      <div class="message-box" @click="openActionSheet">

        <!-- Message content -->
        <div class="message-container" :style="message.type === 'forum_post' ? 'width: 100%' : ''">
          <div class="message-bubble" 
          :dynClass="isGroupped ? 'is-groupped' : ''" 
          :style="isMine ? 'background: '+(message.type === 'forum_post' ? '#eaeaf2' : category.color)+' !important' : ''">
            <ion-img class="image-in-bubble" v-if="messageImageSet.length === 1" :src="messageImageSet[0]" /> 

            <ion-slides 
              v-if="messageImageSet.length > 1"
              pager="true" 
              ref="slider"
              :options="sliderOpts"
              class="loc-slides"                         
              v-on:ionSlideTap="slideTapped($event)"
              v-on:ionSlideDidChange="setSliderActiveIndex()">
              <ion-slide v-for="(img, key) in messageImageSet" :key="key">
                <img :src="img"/>
              </ion-slide>
            </ion-slides>

            <!-- Introduction Box -->
            <div 
              v-if="message.type === 'introduction'" 
              class="introduction-box text-in-bubble" 
              @click.stop="!message.user.isDeleted ? $emit('introductionClicked', message) : null"
            >
              <span class="avatar-box">
                <img :src="message.user.avatar" class="introduction-avatar" />
              </span> 
              <span class="content-box">
                <div class="name">{{ message.user.name }} <div v-if="message.user.isDeleted" class="user-left-flag">~left the conversation</div></div>
                <!-- <div v-if="message.user.bio" class="bio">{{ message.user.bio.substring(0, 160) }}...</div> -->
                <div class="view-profile-button">View Profile</div>
              </span> 
            </div>  

            <!-- Message -->
            <div class="text-in-bubble">
              <span v-if="message.subject" class="message-subject">{{message.subject}}<br></span>
              <span v-if="message.text" class="message-body" v-html="message.text"></span>
              <span v-if="message.description" v-html="message.description"></span>
              <span v-if="message.tags && message.tags.length > 0" class="message-tags">
                <span v-for="tag in message.tags" :key="`${tag.value}_1`">{{tag.display_name}} </span>
              </span>
            </div>

            <!-- Introduction Accept/Reject -->
            <div 
              v-if="message.type === 'introduction' && !isSenderParticipant && isMeOwner && !message.user.isDeleted" 
              class="introduction-box bottom"
            >
              <span class="button reject" v-bind:disabled="!message.user.isDeleted" @click.stop="reject">Reject</span> 
              <span class="button accept" v-bind:disabled="!message.user.isDeleted" @click.stop="accept">Accept</span> 
            </div>

            <!-- Comments button -->
            <div v-if="message.type === 'forum_post'" class="comments-in-bubble">
              <div 
                class="comment-button" 
                v-if="commentsPage === 0 && !message.commentsCount"
                @click.stop="loadComments()"
              >comments</div>
              <div 
                class="comment-button" 
                v-if="commentsPage === 0 && message.commentsCount"
                @click.stop="loadComments()"
              >comments ({{message.commentsCount}})</div>
              <div 
                class="comment-button" 
                v-if="commentsPage > 0"
                @click.stop="hideComments()"
              >hide</div>
            </div>

            <!-- Comments -->
            <div v-if="message.type === 'forum_post' && commentsPage > 0" class="comments-in-bubble">
              <reco-chat-comments 
                :me="me" 
                :comments="comments" 
                :isMeOwner="isMeOwner" 
                @sendComment="$emit('sendComment', { comment: $event, messageId: message.id })"
              />
            </div>

          </div>
          <span v-if="message.type === 'forum_post' || !isTimeGroupped" class="time-container">{{datetime}}</span>
        </div>

      </div>
    </ion-item>
  </div>
</template>

<script lang="ts">
import moment from 'moment';
import RecoChatComments from '@/components/complex/RecoChatComments.vue';

export default {
  components: {
    RecoChatComments
  },
  props: {
    isTempChat: {
      type: Boolean,
      default: false,
    },
    isMeOwner: {
      type: Boolean,
      default: false,
    },
    isMeAdmin: {
      type: Boolean,
      default: false,
    },
    isSenderParticipant: {
      type: Boolean,
      default: true,
    },
    me: {
      type: Object,
    },
    message: {
      type: Object,
    },
    prevMessage: {
      type: Object,
    },
    nextMessage: {
      type: Object,
    },
    category: {
      type: Object,
    },
    groupingTimeLimit: {
      type: Number,
      default: 240 * 1000,
    },
    comments: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      commentsPage: 0,
       sliderOpts: {
        zoom: {
          maxRatio: 3,
          toggle: true,
        },
        initialSlide: 1, 
        speed: 400,
      }
    }
  },
  computed: {
    isMine() {
      return this.message.user.uid == this.me.uid;
    },
    newDay() {
      if (this.prevMessage) {
        if (moment(this.message.tstamp).format('ddd D MMM') !== moment(this.prevMessage.tstamp).format('ddd D MMM')) {
          return moment(this.message.tstamp).format('ddd D MMM');
        }
        return null;
      }
      return moment(this.message.tstamp).format('ddd D MMM');
    },
    isGroupped() {
      if (this.prevMessage && this.prevMessage.user.uid == this.message.user.uid && this.message.tstamp - this.prevMessage.tstamp < this.groupingTimeLimit) {
        return true;
      }
      return false;
    },
    isTimeGroupped() {
      if (this.nextMessage && this.nextMessage.user.uid == this.message.user.uid && this.nextMessage.tstamp - this.message.tstamp < this.groupingTimeLimit) {
        return true;
      }
      return false;
    },
    datetime() {
      // let lengthOfTstamp = this.message.tstamp.toString().length;
      // let messageTstamp = lengthOfTstamp > 13 ? this.message.tstamp : this.message.tstamp * 1000;
      let messageTstamp = moment(this.message.tstamp).unix()*1000;
      /* let currentTstamp = moment().unix()*1000;

      // More than a week ago
      if(messageTstamp < currentTstamp - 7*24*60*60*1000) {
        return moment(messageTstamp).format('MMM D');
      }

      // More than a day ago
      if(messageTstamp < currentTstamp - 24*60*60*1000) {
        return moment(messageTstamp).format('ddd h:mma');
      } */

      // Less than a day ago
      return moment(messageTstamp).format('H:mm');
    },
    messageImageSet(){
      if( Array.isArray(this.message.image)){
        return this.message.image;
      }
      else if(this.message.image && this.message.image.length > 0){
        return [this.message.image];
      }
      return [];
    }    
  },
  methods: {
    accept() {
      if(this.isTempChat) {
        this.presentAreYouSureAlert(
          `Do you want to start a conversation with <b>${this.message.user.name}</b>?`, 
          () => this.$emit('acceptRequest', this.message),
        );
      } else {
        this.presentAreYouSureAlert(
          `Do you want <b>${this.message.user.name}</b> to join this chat?`, 
          () => this.$emit('acceptRequest', this.message),
        );
      }
    }, 
    reject() {
      if(this.isTempChat) {
        this.presentAreYouSureAlert(
          `Are you sure you do not want to start a conversation with <b>${this.message.user.name}</b>?`, 
          () => this.$emit('rejectRequest', this.message),
        );
      } else {
        this.presentAreYouSureAlert(
          `Are you sure you do not want <b>${this.message.user.name}</b> to join this chat?`, 
          () => this.$emit('rejectRequest', this.message),
        );
      }
    },
    presentAreYouSureAlert(message, callback) {
      return this.$ionic.alertController
        .create({
          header: '',
          message,
          buttons: [
            {
              text: 'No',
              role: 'cancel',
            },
            {
              text: 'Yes',
              handler: () => {
                callback();
              },
            },
          ]
        })
        .then(a => a.present());
    },
    loadComments() {
      this.$emit('loadComments', { messageId: this.message.id, commentsPage: this.commentsPage });
      this.commentsPage++;
    },
    hideComments() {
      this.commentsPage = 0;
      this.$emit('hideComments', { messageId: this.message.id });
    },
    openActionSheet() {
      const buttons = [];
      if ((this.isMeOwner || this.isMeAdmin || this.isMine) && this.message.type === 'forum_post') {
        buttons.push({
          text: 'Delete',
          role: 'destructive',
          handler: () => {
            this.deleteMessageAlert();
          },
        });
      } else if(!this.isMine){
        buttons.push({
          text: 'Report',
          role: 'destructive',
          handler: () => {
            this.openReportModal();
          },
        });
      }
      buttons.push({
        text: 'Copy text',
        role: 'none',
        handler: () => {
          this.copyTextToClipboard();
        }
      });
      return this.$ionic.actionSheetController
        .create({ buttons })
        .then(a => a.present())
    },
    openReportModal() {
      return this.$ionic.alertController
        .create({
          header: 'Checkbox',
          inputs: [
            { type: 'checkbox', label: 'Racist', value: 'racist' },
            { type: 'checkbox', label: 'Abusive', value: 'abusive' },
            { type: 'checkbox', label: 'Aggressive', value: 'aggressive' },
            { type: 'checkbox', label: 'Spam', value: 'spam' },
            { type: 'checkbox', label: 'Other', value: 'other' },
          ],
          buttons: [
            {
              text: 'Cancel',
              role: 'cancel',
              cssClass: 'secondary',
            },
            {
              text: 'Report',
              handler: response => {
                this.$emit("reportMessage", { message: this.message, response });
              },
            },
          ],
        })
        .then(a => a.present())
    },
    deleteMessageAlert() {
      return this.$ionic.alertController
        .create({
          header: 'Delete Message',
          message: 'Are you sure you want to delete this forum message?',
          buttons: [
            {
              text: 'Cancel',
              role: 'cancel',
              cssClass: 'secondary',
            },
            {
              text: 'Yes',
              handler: () => {
                this.$emit('deleteMessage', this.message);
              },
            },
          ],
        })
        .then(a => a.present())
      },
    copyTextToClipboard(){
      navigator.clipboard.writeText(this.message.text);
      
    },
    slideTapped($event) {
      $event.target.swiper.zoom.toggle();
    },
    setSliderActiveIndex() {
      this.$refs.slider.getActiveIndex().then((index) => {
        this.currentSlideIndex = index;
      });
    }
  },
}
</script>

<style scoped lang="css">
  .loc-item {
    --padding-start: 10px;
    --padding-end: 0px;
  }
  .loc-item .message-box {
    width: 100%;
    display: flex;
  }
  .loc-item[dynClass~=is-mine] .message-box {
    justify-content: flex-end;
  }
  .loc-item .avatar-container {
    display: flex;
    width: 45px;
    padding-top: 5px;
    padding-left: 5px;
  }
  .loc-item .message-container {
    display: flex;
    flex-direction: column;
    /* width: calc(100% - 45px); */
  }
  .loc-item .time-container {
    display: inline-block;
    width: 100%;
    min-width: 36px;
    font-size: 11px;
    line-height: 13px;
    color: #666;
    text-align: left;
    margin-bottom: 6px;
    padding-left: 3px;
  }
  .loc-item[dynClass~=is-mine] .time-container {
    text-align: right;
    padding-right: 3px;
  }
  .loc-item .message-container .message-bubble {
    width: 100%;
    overflow: hidden;
    -webkit-margin-start: 0px;
    margin-inline-start: 0px;
    -webkit-margin-end: 0px;
    margin-inline-end: 0px;
    border-radius: 5px;
    margin-top: 4px;
  }
  .loc-item.new-day {
    font-weight: bold;
    text-align: center;
    font-size: 14px;
    margin-top: 18px;
    color: #444;
  }
  .loc-item.user {
    margin-top: 10px;
  }
  .loc-item.user .sender-name {
    display: inline-block;
    font-size: 15px;
    font-weight: bold;
    margin-left: 10px;
    color: #444;
  }
  .message-bubble .text-in-bubble {
    display: block;
    padding: 8px 12px;
    font-size: 16px;
    line-height: 22px;
    word-wrap: break-word !important;
    max-width: 95vw;
  }
  .message-bubble .comments-in-bubble {
    padding: 0px 12px 8px 12px;
    font-size: 16px;
    overflow: hidden;
  }
  .message-bubble .comments-in-bubble .comment-button {
    font-size: 14px;
    font-weight: 500;
    text-decoration: underline;
    cursor: pointer;
    color: #0399FF;
    float: right;
  }
  .loc-item[dynClass~=is-mine] .message-bubble .comments-in-bubble .comment-button {
    color: #fff;
  }
  .message-bubble .comments-in-bubble .comment-button:active {
    position: relative;
    top: 2px;
  }
  .loc-item[dynClass~=is-mine] .message-bubble {
    max-width: 100%;
    color: #fff;
  }
  .loc-item[dynClass~=is-not-mine] .message-bubble {
    background: #f2f2f4;
  }
  .user-container {
    display: flex;
  }
  .loc-item .loc-avatar {
    display: block;
    height: 34px;
    width: 34px;
    margin-top: 4px;
    margin-right: 0px;
    background: #fff !important;
  }
  .user-container .name {
    line-height: 32px;
    font-size: 16px;
    font-weight: bold;
  }
  .message-subject {
    font-weight: 600;
    display: block;
  }
  .message-tags {
    display: block;
    font-size: 14px;
    font-weight: 600;
    text-transform: uppercase;    
  }

  /* introduction box */
  .introduction-box {
    width: 95vw;
    display: flex;
    /* border-bottom: 1px solid #ddd; */
  }
  .introduction-box.bottom {
    border-bottom: none;
    justify-content: space-around;
    /* border-top: 1px solid #ddd; */
  }
  .avatar-box {
    float:left;
  }
  .introduction-box .introduction-avatar {
    display: block;
    height: 90px;
    width: 90px;
    margin-top: 4px;
    margin-right: 10px;
    border-radius: 45px;
  }
  .introduction-box .content-box {
    width: calc(100% - 100px);
  }
  .introduction-box .content-box .name {
    font-weight: bold;
    margin-bottom: 6px;
  }
  .loc-item[dynClass~=is-mine] .introduction-box .content-box .name {
    color: #e2e2e2;
  }
  .introduction-box .content-box .bio {
    font-size: 13px;
    line-height: 18px;
    color: #666;
    margin-bottom: 6px;
  }
  .loc-item[dynClass~=is-mine] .introduction-box .content-box .bio {
    color: #e2e2e2;
  }
  .introduction-box .content-box .view-profile-button {
    font-size: 13px;
    font-weight: bold;
    color: #ed1556;
  }
  .loc-item[dynClass~=is-mine] .introduction-box .content-box .view-profile-button{
    color: #eee;
  }
  .introduction-box.bottom .button {
    margin: 6px 0;
    padding: 5px 15px;
    min-width: 120px;
    text-align: center;
    border-radius: 5px;
    color: #fff;
  }
  .introduction-box.bottom .button.accept {
    background: #11c456;
    width: 35vw;
  }
  .introduction-box.bottom .button.reject {
    background: var(--ion-color-danger);
    margin-right: 15px;
    width: 35vw;
  }
  .introduction-box.bottom .button:active {
    position: relative;
    top: 2px;
  }
  .admin-option-button {
    display: inline-block;
    text-transform: uppercase;
    font-weight: 600;
    padding: 10px 0px;
  }
  .admin-option-button.delete {
    color: #e84118;
    margin-right: 10px;
  }
  .admin-option-button.report {
    color: #333;
  }
  .user-left-flag{
    font-size: 10px;
    color: #666;
  }
  .loc-slides {
    position: relative;
    width: 95vw;
    z-index: 11;
    --bullet-background: var(--actiways-primary-color);
    --bullet-background-active: var(--actiways-primary-color);
  }
</style>