<template>
  <reco-modal 
    v-on:backButtonClicked="backButtonClicked" 
    v-on:doneButtonClicked="doneButtonClicked" 
    :withBackButton="locMotto.length ? isInitialSteps : true"
    :isNextButton="false" 
    :withDoneButton="false"
    :title="title">
    <!-- :withDoneButton="locMotto.length ? true : false"  -->

    <ion-content slot="content">

       <button :class="locMotto.length < 2 ? 'loc-next-btn disabled' : 'loc-next-btn'" 
               @click="doneButtonClicked"
               :disabled="locMotto.length < 2">
                  Next <b-icon class="loc-next-icon" icon="chevron-right" />
        </button>  

      <ion-list lines="none">

        <!-- Write Motto -->
        <ion-item class="loc-item">
          <ion-label class="loc-label" style="padding-bottom: 0px">Subject</ion-label>
          <div class="char-counter">
            <span class="chars">{{locMotto.length}}</span><span class="max-chars">/30</span>
          </div>
        </ion-item>
        <ion-item class="loc-item">
          <ion-input ref="mottoInput"
          class="loc-input"
            placeholder="Type your post subject here..." 
            :maxlength="30"
            inputmode="text"
            v-on:ionInput="event => locMotto = event.target.value"
            :value="locMotto"
          />
        </ion-item>

        <!-- Write Description -->
        <ion-item class="loc-item">
          <ion-label class="loc-label" style="padding-bottom: 0px">Description</ion-label>
        </ion-item>
        <ion-item class="loc-item">
          <ion-textarea 
            ref="descriptionInput" 
            class="loc-input-textarea"
            placeholder="Type your optional post description here..." 
            :rows="4" 
            inputmode="text"
            v-on:ionInput="event => locDescription = event.target.value"
            :value="locDescription"
          />
          <!-- <reco-text-editor :textChanged="onTextChanged" :text="locDescription"/> -->
        </ion-item>

        <!-- post language -->
        <ion-item>
          <ion-label class="loc-label">You are posting in:</ion-label>
           <ion-select 
            :style="{ color }"
            v-on:ionChange="onChangePostLanguage($event)"
            :value="selectedLanguage.shortCode" 
            interface="popover">
            <ion-select-option
              v-for="(language, idx) in languageOptions" 
              :key="idx" 
              :value="language.shortCode">
              {{language.name}}
            </ion-select-option>
          </ion-select>
        </ion-item>

        <!-- Response Type -->
        <ion-item class="loc-item" v-if="!excludedFeatures.includes('group-response')">
          <ion-label class="loc-label">Type of Communication</ion-label>
        </ion-item>
        <ion-item class="loc-item" v-if="!excludedFeatures.includes('group-response')">
          <div class="rt-bubble-container">
            <div 
              v-for="chat in !activeFeatures.includes('forum') ? chatTypes.filter(t => t.value !== 'forum') : chatTypes"
              class="rt-bubble" 
              :class="chat.value === chatType.value ? 'active' : ''"  
              :key="chat.value"
              :style="chat.value === 'forum' ? 'margin-right: 10px' : ''"
              @click="chatType = chat">
              {{chat.display_name}}
            </div>
          </div>
        </ion-item>


        <ion-item class="loc-item">
          <ion-label class="loc-label" style="padding-bottom: 0px">Number of responses</ion-label>
        </ion-item>
        <ion-item>
          <ion-range 
            v-show="chatType.value !== 'forum'"
            ref="responseIonRange" 
            :min="rp.min" :max="rp.max" :step="rp.step" 
            class="loc-ranger"
            :style="`--bar-background-active: ${color}`"
            v-on:ionChange="($event) => maxResponses = $event.detail.value" 
            :value="maxResponses">
            <ion-label class="range-label" slot="end" v-if="maxResponses === 13">Unlimited</ion-label>
            <ion-label class="range-label" slot="end" v-else >{{maxResponses}} {{maxResponses > 1 ? 'people' : 'person'}}</ion-label>
          </ion-range>
          <div class="num-responders-box" v-show="chatType.value === 'forum'">
            <div 
              v-if="activeFeatures.includes('forum100')"
              class="num-responders-button" 
              :class="maxResponses === 100 ? 'active' : ''" 
              @click="maxResponses = 100">100</div> 
            <div 
              v-if="activeFeatures.includes('forum1000')"
              class="num-responders-button" 
              :class="maxResponses === 1000 ? 'active' : ''" 
              @click="maxResponses = 1000">1 000</div> 
            <div 
              v-if="activeFeatures.includes('forum10000')"
              class="num-responders-button"
              :class="maxResponses === 10000 ? 'active' : ''"
              @click="maxResponses = 10000">10 000</div>
            <div 
              v-if="activeFeatures.includes('forum_unlimited')"
              class="num-responders-button" 
              :class="maxResponses === 10000000 ? 'active' : ''"
              @click="maxResponses = 10000000">∞</div>
          </div>
        </ion-item>

        <!-- Expiration setting -->
        <ion-item>
          <ion-label class="loc-label">Validity</ion-label>
          <ion-select 
            :style="{ color }"
            placeholder="Select Expiration" 
            v-on:ionChange="expiration = expirations.find(exp => exp.value === $event.target.value)" 
            :value="expiration.value" interface="popover">
            <ion-select-option
              v-for="expiration in expirations" 
              :key="expiration.value" 
              :value="expiration.value">
              {{expiration.display_name}}
            </ion-select-option>
          </ion-select>
        </ion-item>

	    	<ion-item-divider class="loc-content mid-divider"></ion-item-divider>
        <ion-item>
          <span>Visibility</span>
        </ion-item>
        <!-- Distance setting -->
        <ion-item>
          <ion-label class="loc-label">Distance</ion-label>
          <ion-select
            :style="{ color }"
            placeholder="Select Distance" 
            v-on:ionChange="distance = distances.find(dist => dist.value === $event.target.value)" 
            :value="distance.value" 
            interface="popover">
            <ion-select-option 
              v-for="distance in distances" 
              :key="distance.value" 
              :value="distance.value">
              {{distance.display_name}}
            </ion-select-option>
          </ion-select>
        </ion-item>

        <!-- Age setting -->
        <ion-item>
          <ion-label class="loc-label">Age</ion-label>
          <ion-range 
            ref="ageIonRange" dual-knobs="true" min="18" max="99" step="1" class="loc-ranger"
            :style="`--bar-background-active: ${color}`"
            v-on:ionChange="($event) => age = $event.detail.value" :value="locAge">
              <ion-label class="range-label" slot="start">{{age.lower}}</ion-label>
              <ion-label class="range-label" slot="end">{{age.upper}}</ion-label>
            </ion-range>
        </ion-item>

        <!-- Gender setting -->
        <ion-item>
          <ion-label class="loc-label">Gender</ion-label>
          <ion-select
            :style="{ color }"
            placeholder="Select Gender" 
            v-on:ionChange="gender = genders.find(gen => gen.value === $event.target.value)" 
            :value="gender.value" interface="popover">
            <ion-select-option 
              v-for="gender in genders" 
              :key="gender.value" 
              :value="gender.value">
              {{gender.display_name}}
            </ion-select-option>
          </ion-select>
        </ion-item>

        <ion-item lines="full" style="height: 0px !important; margin-top: 20px;" />

      </ion-list>
    </ion-content>
  </reco-modal>
</template>

<script>
import RecoModal from '@/components/complex/RecoModal.vue';
import modalbuilders from '@/helpers/modalbuilders';
import RecoTextEditor from '@/components/complex/RecoTextEditor.vue';
import Languages from '@/assets/languages';
import { lang } from 'moment';


export default {
  name: 'RecoCreatePostDescription',
  components: {
    RecoModal,
    RecoTextEditor
  },
  watch: {
    locMotto() {
      this.onMottoChange(this.locMotto);
    },
    locDescription() {
      this.onDescriptionChange(this.locDescription);
    },
    gender(val) {
      this.onVisibilityChange('gender', val);
    },
    age(val) {
      this.onVisibilityChange('age', val);
    },
    expiration(val) {
      this.onVisibilityChange('expiration', val);
    },
    distance(val) {
      this.onVisibilityChange('distance', val);
    },
    activityDateTime(val) {
      this.onVisibilityChange('activityDateTime', val);
    },
    maxResponses(val) {
      this.onVisibilityChange('maxResponses', val);
    },
    selectedLanguage(val){
      this.onVisibilityChange('language', val.shortCode);
    },
    chatType(val) {
      this.onVisibilityChange('chatType', val);
      if(val.value === 'forum') {
        setTimeout(() => {
          this.maxResponses = 10000;
          this.$refs.responseIonRange.value = this.maxResponses;
        }, 0);
      } else if (val.value === 'group') {
        setTimeout(() => {
          this.maxResponses = 6;
          this.$refs.responseIonRange.value = this.maxResponses;
        }, 0);
      } else if (val.value === 'single') {
        setTimeout(() => {
          this.maxResponses = 12;
          this.$refs.responseIonRange.value = this.maxResponses;
        }, 0);
      }
    },
    automaticResponse(val) {
      this.onVisibilityChange('automaticResponse', val);
    }
  },
  props: {
    title: {
      type: String,
      default: "Post Settings"
    },
    motto: {
      type: String,
      default: "",
    },
    description: {
      type: String,
      default: "",
    },
    type: {
      type: String,
      default: 'direct',
    },
    doneButtonClicked: {
      type: Function,
      default: () => { return }
    },
    isInitialSteps: {
      type: Boolean,
      default: true,
    },
    backButtonClicked: {
      type: Function,
      default: () => { return }
    },
    doneButtonClicked: {
      type: Function,
      default: () => { return }
    },
    withBackButton: {
      type: Boolean,
      default: true,
    },
    withDoneButton: {
      type: Boolean,
      default: false,
    },
    visibility: {
      type: Object
    },
    category: {
      type: Object
    },
    expirations: {
      type: Array,
      default() {
        return [
          {value: "half_an_hour", display_name: "30 min", seconds: 1800},
          {value: "one_hour", display_name: "1 h", seconds: 3600},
          {value: "three_hour", display_name: "3 h", seconds: 10800},
          {value: "six_hour", display_name: "6 h", seconds: 21600},
          {value: "twelve_hours", display_name: "12 h", seconds: 43200},
          {value: "one_day", display_name: "1 day", seconds: 86400},
          {value: "three_days", display_name: "3 days", seconds: 259200},
          {value: "seven_days", display_name: "1 week", seconds: 604800},
        ];
      }
    },
    distances: {
      type: Array,
      default() {
        return [
          // {value: "50_meters", display_name: "50 m", meters: 50},
          // {value: "100_meters", display_name: "100 m", meters: 100},
          // {value: "300_meters", display_name: "300 m", meters: 300},
          {value: "500_meters", display_name: "500 m", meters: 500},
          {value: "1_km", display_name: "1 km", meters: 1000},
          {value: "3_km", display_name: "3 km", meters: 3000},
          {value: "5_km", display_name: "5 km", meters: 5000},
          {value: "10_km", display_name: "10 km", meters: 10000},
        ];
      },
    },
    chatTypes: {
      type: Array,
      default() {
        return [
          {value: "single", display_name: "Private Chat"},
          {value: "group", display_name: "Small Group"},
          {value: "forum", display_name: "Large Forum"},
        ];
      }
    },
    genders: {
      type: Array,
      default() {
        return [
          { value: 'all', display_name: 'All' },
          { value: 'male', display_name: 'Male' },
          { value: 'female', display_name: 'Female' }
        ];
      }
    },
    excludedFeatures: {
      type: Array,
      default() {
        return [];
      },
    },
    activeFeatures: {
      type: Array,
      default() {
        return [];
      },
    },
    color: {
      type: String,
    },
    me:{
      type: Object,
      default(){
        return null
      }
    },
    selectedLanguage:{
      type: String,
      default: ""
    },
    languageOptions:{
      type: Array,
      default(){
        return [];
      }
    },
    languages: {
      type: Array,
      default() {
        return Languages;
      }
    },
    preSelectedLanguage:{
      type: String,
      default: ''
    },
    postLanguageChanged:{
      type: Function,
      default(){
        return;
      }
    }
  },
  data() {
    return {
      locMotto: this.motto,
      locDescription: this.description,
      gender: this.visibility.gender,
      locType: 'direct',
      age: this.visibility.age,
      locAge: this.visibility.age,
      expiration: this.visibility.expiration,
      distance: this.visibility.distance,
      activityDateTime: this.visibility.activityDateTime,
      maxResponses: this.visibility.maxResponses,
      chatType: this.visibility.chatType,
      automaticResponse: this.visibility.automaticResponse
    }
  },
  computed: {
    audienceText() {
      const gender = this.gender.value == 'all' ? "any gender" : this.gender.value+" users";
      const age = this.age.lower == 18 && this.age.upper == 99 ? "above 18" : "between "+this.age.lower+" and "+this.age.upper;
      return "to "+gender+" "+age;
    },
    expirationText() {
      // const activityDateTime = !this.activityDateTime ? "The date/time of the activity is not set" : "The activity will take place on "+moment(this.activityDateTime).format('DD MMM YYYY')+" at "+moment(this.activityDateTime).format('HH:mm')
      if (this.locType === 'direct') {
        return "for "+this.expiration.display_name.toLowerCase()/*+activityDateTime+"."*/;
      }
      return "for unlimited time";
    },
    locationText() {
      if (this.locType === 'direct') {
        return this.distance.display_name.toLowerCase();
      }
      return 'unlimited distance';
    },
    responseTypeText() {
      if (this.locType === 'direct') {
        return this.maxResponses == 1 ? "One person " : this.maxResponses+" people ";
      }
      return "unlimited people ";
      // const chat = this.chatType.value == "single" ? "in "+(this.maxResponses > 1 ? this.maxResponses : "a")+" single chat"+(this.maxResponses != 1 ? "s" : "") : "in a group chat";
      // const response = this.automaticResponse && this.maxResponses > 1 && this.chatType.value == "single" ? "Automatic response is set" : "No automatic response set";
      // return people+" can reply to this post<br>"+chat;
    },
    rp() {
      if (this.chatType.value === 'forum') {
        return { min: 100, max: 10000000, step: 100 };
      } else if (this.chatType.value === 'group') {
        return { min: 2, max: 12, step: 1 };
      }
      return { min: 1, max: 13, step: 1 };
    }
  },
  mounted() {
    this.$refs.ageIonRange.value = this.age;
    if (!this.excludedFeatures.includes('infinite-distance')) {
      this.distances.push({value: "infinite", display_name: "∞ km", meters: 100000000});
    }
    if (!this.excludedFeatures.includes('infinite-expiration')) {
      this.expirations.push({value: "forever", display_name: "Until Deletion", seconds: 9999999999});
    }

    this.selectedLanguage = this.preSelectedLanguage ? this.languages.find(lang => lang.shortCode === this.preSelectedLanguage) : this.languages.find(lang => lang.shortCode === this.me.languages.post_language);
    for(const langCode of this.me.languages.spoken_languages){
      let language = this.languages.find(l => l.shortCode === langCode);
      if(language){
        this.languageOptions.push(language);
      }
    }
  },
  methods: {

    // select audience
    openAudienceSelect() {
      return modalbuilders.buildAudienceSelect(this);
    },

    // select expiration
    openExpirationSelect() {
      if (this.locType === 'direct') {
        return modalbuilders.buildExpirationSelect(this);
      }
    },

    // select distance
    openLocationSelect() {
      if (this.locType === 'direct') {
        return modalbuilders.buildLocationSelect(this); 
      }
    },

    // select response type
    openResponseTypeSelect() {
      if (this.locType === 'direct') {
        return modalbuilders.buildResponseTypeSelect(this); 
      }
       
    },
    onTextChanged(content){
      this.locDescription = content;
    },
    onChangePostLanguage(event){
       this.selectedLanguage = this.languageOptions.find(lang => lang.shortCode === event.target.value);
       this.postLanguageChanged(this.selectedLanguage);
    }
  }
}
</script>

<style lang="css">
  ion-select {
    font-weight: 500;
  }
  .loc-item {
    font-size: 16px;
  }
  .intro {
    font-size: 17px;
    line-height: 28px;
  }
  .loc-label {
    padding: 5px 0;
    font-weight: 500;
  }
  .range-label {
    font-weight: 500;
  }
  .item-title {
    padding-top: 10px;
    font-weight: bold;
  }
  .item-option {
    font-size: 16px;
    line-height: 22px;
    --inner-padding-bottom: 8px;
    --inner-padding-top: 6px;
  }
  .type-button {
    --background: #eee;
    --color: #888;
  }
  .type-button.active {
    --color: #fff;
  }
  .loc-ranger {
    --bar-height: 2px;
  }
  .loc-input {
    --inner-padding-top: 8px;
    --inner-padding-bottom: 8px;
    --placeholder-color: var(--reco-lighter-font-color);
    --placeholder-opacity: 0.66;
  }
  .loc-input-textarea {
    padding: 8px 0;
  }
  .char-counter {
    color: #636e72;
  }
  .char-counter .chars {
    font-weight: 600;
    color: #455054;
  }
  .char-counter .max-chars {
    font-size: 12px;
  }
  .rt-bubble-container {
    display: flex;
    width: 100%;
    justify-content: space-between;
    padding-bottom: 8px;
  }
  .rt-bubble-container .rt-bubble {
    box-sizing: border-box;
    width: 80px;
    height: 80px;
    border-radius: 45px;
    text-align: center;
    padding: 20px 8px;
    border: 2px solid #343434;
    font-size: 14px;
    font-weight: 600;
  }
  .rt-bubble-container .rt-bubble.active {
    color: #ED1656;
    border: 2px solid #ED1656;
  }
  .num-responders-box {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    margin: 8px 0 16px 0;
  }
  .num-responders-box .num-responders-button {
    border: 2px solid #343434;
    width: 70px;
    height: 34px;
    line-height: 30px;
    text-align: center;
    font-weight: 500;
    font-size: 14px;
    border-radius: 17px;
  }
  .num-responders-box .num-responders-button.active {
    color: #ED1656;
    border: 2px solid #ED1656;
  }
  .mid-divider {
  	min-height: 10px;
  }
  .loc-next-btn{
    position: fixed;
    right: 8px;
    bottom: 9px;
    max-width: 140px;
    max-height: 42px;
    line-height: 36px;
    font-weight: bold;
    font-size: 16px;
    border-radius: 10px;
    text-align: center;
    background: var(--actiways-primary-color); 
    color: #fff;
    z-index: 999;
    padding-left: 10px;
    width: 120px;
  }
  .loc-next-icon{
    position: relative;
    top: 2px;
  }
  .disabled{
    background: #f58ead;
  }
</style>
