<template>

  <reco-modal 
    v-on:backButtonClicked="onModalClose()"
    :withBackButton="true" 
    v-on:doneButtonClicked="clearFiltersClicked"
    :withDoneButton="true"
    doneButtonText="Clear"
    title="Filter Posts">

    <!-- Menu sections -->  
    <ion-content slot="content">
      <ion-list lines="none">

          <!-- Select Tags -->
          <ion-item-divider class="loc-content mid-divider"></ion-item-divider>
          <ion-item class="loc-item" @click="openRecoTagSelect()" :disabled="profilesOnly || onTheSpotOnly || businessOnly">
            <ion-label class="loc-label">Topics</ion-label>
            <span v-if="showSelect" class="loc-tagselect-btn">Select</span>
            <span v-else>
              <reco-tag 
                :category="{ color }"
                :tag="tags.filter(t => t.is_recommended)[0]"
                style="top:0px"
              />
            </span>
          </ion-item>

          <ion-item class="loc-item-tags" v-if="otherTags(tags).length" @click="openRecoTagSelect()">
            <div style="overflow-x: scroll; height: 36px; margin-left: 4px">
              <div :style="'width: '+getTagContainerWidth()+'; height: 36px'">
                <reco-tag 
                  v-for="tag in otherTags(tags)" 
                  :category="{ color }"
                  :key="tag.display_name" 
                  :tag="tag" 
                />
              </div>
            </div>
          </ion-item>

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

          <!-- Select Posted At -->
          <ion-item-divider class="loc-content mid-divider"></ion-item-divider>
          <ion-item class="loc-item" v-if="!recoDate">
            <ion-label class="loc-label">Posted at</ion-label>
            <ion-select 
              placeholder="Select Post Age" 
              :style="{ color }"
              v-on:ionChange="onSelectExpiration($event.target.value)" 
              :value="expiration.value" 
              interface="popover">
              <ion-select-option v-for="e in expirations" :key="e.value" :value="e.value">
                {{e.display_name}}
              </ion-select-option>
            </ion-select>
          </ion-item>

          <!-- Select Age -->
          <ion-item-divider class="loc-content mid-divider"></ion-item-divider>
          <ion-item class="loc-item" :disabled="businessOnly">
            <ion-label class="range-label">Age</ion-label>

            <ion-select 						
                v-on:ionChange="onChangeAgeLower($event.target.value)"    
                :value="locAge.lower"              
                interface="popover">
                <ion-select-option                 
									v-for="ageItem in ageList" 
									:key="ageItem" 
									:value="ageItem">
									{{ageItem}}
								</ion-select-option>
              </ion-select>

            <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) => onChangeAge($event.detail.value)"
               v-on:ionBlur="age = locAge"
             >  
              </ion-range>

              <ion-select 						
                v-on:ionChange="onChangeAgeUpper($event.target.value)"                             
                :value="locAge.upper"              
                interface="popover">
                <ion-select-option 
									v-for="ageItem in ageList" 
									:key="ageItem" 
									:value="ageItem">
									{{ageItem}}
								</ion-select-option>
              </ion-select>

          </ion-item>

          <!-- Select gender -->
          <ion-item-divider class="loc-content mid-divider"></ion-item-divider>
          <ion-item class="loc-item" :disabled="businessOnly">
            <ion-label class="loc-label">Gender</ion-label>
            <ion-select 
              placeholder="Select Expiration" 
              :style="{ color }"
              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>

        <!-- Profiles only -->
        <ion-item-divider class="loc-content mid-divider"></ion-item-divider>
        <ion-item class="loc-item">
            <ion-label class="loc-label">See Profiles only</ion-label>
				    <ion-toggle class="loc-toggle" @ionChange="profilesOnly = !profilesOnly" :checked="profilesOnly" :disabled="onTheSpotOnly || businessOnly"></ion-toggle>
        </ion-item>

        <!-- On the Spot posts only -->
        <ion-item-divider class="loc-content mid-divider"></ion-item-divider>
        <ion-item class="loc-item">
            <ion-label class="loc-label">See posts On the Spot only</ion-label>
				    <ion-toggle class="loc-toggle" @ionChange="onTheSpotOnly = !onTheSpotOnly" :checked="onTheSpotOnly" :disabled="profilesOnly || businessOnly"></ion-toggle>
        </ion-item>

         <!-- Businesses only -->
        <ion-item-divider class="loc-content mid-divider"></ion-item-divider>
        <ion-item class="loc-item">
            <ion-label class="loc-label">See Businesses only</ion-label>
				    <ion-toggle class="loc-toggle" @ionChange="businessOnly = !businessOnly" :checked="businessOnly" :disabled="profilesOnly || onTheSpotOnly"></ion-toggle>
        </ion-item>

      </ion-list>
    </ion-content>

  </reco-modal>
</template>

<script lang="ts">
import RecoTag from '@/components/atomic/RecoTag.vue';
import modalbuilders from '@/helpers/modalbuilders';
import animations from '@/animations';
import RecoModal from '@/components/complex/RecoModal.vue';

export default {
  components: {
    RecoTag,
    RecoModal,
  },
  props: {
    side: {
      type: String,
      default: "end",
    },
    menuId: {
      type: String,
      default: "recoPostFilters",
    },
    type: {
      type: String,
      default: "mainFeed",
    },
    getTags: {
      type: Function,
    },
    padding: {
      type: Boolean,
      default: true,
    },
    closeMenu: {
      type: Boolean,
      default: false,
    },
    genders: {
      type: Array,
      default() {
        return [
          {value: "all", display_name: "All"},
          {value: "male", display_name: "Male"},
          {value: "female", display_name: "Female"},
        ];
      }
    },
    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 kms", display_name: "3 km", meters: 3000},
          {value: "5 kms", display_name: "5 km", meters: 5000},
          {value: "10 kms", display_name: "10 km", meters: 10000},
          {value: "infinite", display_name: "∞ km", meters: 100000000},
        ];
      },
    },
    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},
          {value: "forever", display_name: "All", seconds: 9999999999}
        ];
      }
    },
    allTags: {
      type: Array,
      default() {
        return []
      }
    },
    filters: {
      type: Object,
    },
    numOfPosts: {
      type: String,
    },
    color: {
      type: String,
      default: "#ed1556"
    },
    excludedFeatures:{
      type: Array,
      default(){
        return [];
      }
    },
    recoDate:{
      type: Boolean,
      default: false
    },
    businessOnlySelected: {
      type: Function,
      default: () => {return;}
    },
  },
  data() {
    return {
      // filters
      distance: this.filters.distance,
      tags: this.filters.tags,
      gender: this.filters.gender,
      age: this.filters.age,
      expiration: this.filters.posted_at,

      // helpers
      tagSelectModal: null,
      locAge: this.filters.age,
      modalOpened: false,
      profilesOnly: false,
      onTheSpotOnly: false,
      businessOnly: false
    }
  },
  mounted() {
    setTimeout(() => {
      this.$refs.ageIonRange.value = this.age;
    }, 500);
    this.setToggleButtons();
  },
  watch: {
    distance() {
      if (this.isSubmittable) {
        this.distanceChanged(this.distance);
      }
    },
    gender() {
      if (this.isSubmittable) {
        this.genderChanged(this.gender);
      }
    },
    age() {
      if (this.isSubmittable && this.$refs.ageIonRange) {
        this.ageChanged(this.age);
      }
    },
    expiration() {
      if (this.isSubmittable) {
        this.expirationChanged(this.expiration);
      }
    },
    filters: {
      deep: true,
      handler() {
        // filters
        console.log('FILTERS FROM RECOMPONENTS: ', this.filters);
        this.distance = this.filters.distance;
        this.tags = this.filters.tags;
        this.gender = this.filters.gender;
        this.age = this.filters.age;
        this.locAge = this.filters.age;
        this.expiration = this.filters.posted_at;
      }
    },
    profilesOnly(){
      if(this.profilesOnly){
        this.tags = [{display_name: "Profile", is_recommended: true, matching: false, value: "profile"}]      
      }        
      else{
        this.tags = [];
      }
      this.tagsChanged(this.tags);
    },    
    onTheSpotOnly(){
      if(this.onTheSpotOnly){
        this.tags = [{display_name: "On the Spot", is_recommended: true, matching: false, value: "on_the_spot"}]
      } 
      else{
        this.tags = [];
      }
      this.tagsChanged(this.tags);
    },
    async businessOnly(){
      if(this.businessOnly){
        this.tags = [{display_name: "Business", is_recommended: true, matching: false, value: "business"},]      
      } 
      else{
        this.tags = [];
      }
      this.tagsChanged(this.tags);
    }
  },
  computed: {
    tagsText() {
      return this.tags.length+" tags are selected";
    },

    /* decides whether the filters are valid */
    isSubmittable() {
      return true;
    },
    ageList(){
      let list = [];
      for(let i = 18; i <= 99; i++){
        list.push(i);
      }
      return list;
    },
    showSelect(){
      if(!this.tags.filter(t => t.is_recommended).length ||
          this.tags.filter(t => t.is_recommended)[0].value === "profile" ||
          this.tags.filter(t => t.is_recommended)[0].value === "on_the_spot" ||
          this.tags.filter(t => t.is_recommended)[0].value === "business") return true;
      return false;
    }
  },
  methods: {
    onModalClose(){
      this.age = this.locAge;
      if(this.businessOnly){
        this.businessOnlySelected();
      }
      this.backButtonClicked();
    },
    openRecoTagSelect() {
      this.modalOpened = true;
      return modalbuilders.buildTagFilterSelect(this, {
          enterAnimation: animations.defaultEnter,
          leaveAnimation: animations.defaultLeave,
        }, {
          backButtonClicked: () => {
            this.modalOpened = false;
            this.tagSelectModal.dismiss();
          },
      });
    },

    otherTags(tags) {
      return tags.filter(t => !t.is_recommended);
    },

    getTagContainerWidth() {
      let num_of_tags = this.tags.length;
      let letters = 0;
      for (var i = 0; i < num_of_tags; i++) {
        letters += this.tags[i].display_name.length;
      }
      return (letters*12+num_of_tags*16)+'px';
    },

    /* on age is selected */
    onChangeAge(val) {
      this.locAge = val;
      if(this.$refs.ageIonRange){
        this.$refs.ageIonRange.value = val;
      }
    },

    onChangeAgeLower(lower){
      let newAge = {lower: parseInt(lower, 10), upper: this.locAge.upper};
      this.onChangeAge(newAge);
    },

    onChangeAgeUpper(upper){
      let newAge = {lower: this.locAge.lower, upper: parseInt(upper, 10)};        
      this.onChangeAge(newAge);
    },

    // updateAgeProp(newAge){
    //   this.locAge = newAge;
    //   if(this.$refs.ageIonRange){
    //     this.$refs.ageIonRange.value = newAge;
    //   }
    // },

    /* on select distance */
    onSelectDistance(val) {
      this.distance = this.distances.find(distance => distance.value === val);
    },

    /* on select expiration */
    onSelectExpiration(val) {
      this.expiration = this.expirations.find(expiration => expiration.value === val);
    },
    closeFilters() {
      this.$refs.recoPostFilters.close();
    },
    setToggleButtons(){
      if(this.filters && this.filters.tags && this.filters.tags !== []){
        const keyTag = this.filters.tags.filter(t => t.is_recommended)[0];
        if(keyTag && keyTag.value === "profile") this.profilesOnly = true;
        else if(keyTag && keyTag.value === "on_the_spot") this.onTheSpotOnly = true;
        else if(keyTag && keyTag.value === "business") this.businessOnly = true;
      }
    }
  }
}
</script>

<style scoped lang="css">
  .loc-content {
    --background: #fff;
  }
  .loc-item {
    --padding-top: 10px;
    --padding-bottom: 10px;
  }
  .loc-row {
    padding: 4px 0;
  }
  .loc-row-one-line {
    padding: 9px 0;
  }
  .loc-row-with-input {
    padding: 2px 0;
  }
  .loc-col {
    padding: 3px;
  }
  ion-select {
    font-weight: 500;
  }
  .placeholder {
    font-size: 16px;
    color: var(--reco-lighter-font-color);
  }
  .value {
    font-size: 15px;
    font-weight: 600;
  }
  .placeholder .secondary,
  .value .secondary {
    font-size: 13px;
    color: var(--reco-lighter-font-color);
  }
  .icon-container {
    display: inline-block;
    width: 36px;
    line-height: 36px;
    text-align: center;
    border-radius: 18px;
    color: #fff;
    background: red;
  }
  .icon-container.inline {
    margin: 10px 15px 10px 0;
  }
  .right-arrow {
    font-size: 26px;
    color: var(--reco-lighter-font-color);
  }
  .motto-input {
    width: 100%;
    line-height: 24px;
    font-size: 16px;
  }
  .description-input {
    width: 100%;
    line-height: 18px;
    resize: none;
    font-size: 16px;
  }
  .advanced-settings-button {
    font-size: 16px;
    color: var(--ion-color-primary);
  }
  .settings-grid {
    font-size: 14px;
  }
  .section-title {
    font-size: 16px;
    text-transform: uppercase;
    padding: 14px 0 10px 0;
  }
  .section-title.last {
    padding: 9px 0 10px 0;
  }
  .section-ul {
    padding-left: 20px;
    line-height: 26px;
    margin-top: 5px;
    width: 100%;
  }
  .edit-icon {
    position: relative;
    top: 1px;
    margin-left: 3px;
    float: right;
  }
  .mid-divider {
    min-height: 10px;
  }
  .loc-ranger {
    --bar-height: 2px;
  }
  .loc-item-tags {
    margin-top:-15px;
    --padding-start: 6px;
    --padding-end: 6px;
  }
  .loc-label {
    padding: 5px 0;
    font-weight: 500;
  }
  .range-label {
    font-weight: 500;
  }
  .loc-tagselect-btn{
	  border-radius: 4px;
	  background-color: var(--actiways-primary-color);
	  color: #fff;
	  padding: 4px 10px 4px 10px;
	  margin: 4px;
  }
  .loc-toggle{
		--background-checked: #ed1556;
	}
</style>
