<template>
  <div class="bg-white">
    <div class="row q-pa-md">
      <div class="col-3 col-md-3 show" name="qbank">
        <search-filters ref="filter" :searchform="searchform" :appliedFilters="appliedFilters" @removePlanFromFilters="removePlanFromFilters" />
      </div>
      <div class="col-9 col-md-9 col-sm-12 col-xs-12">
        <div class="q-pa-mdd">
          <q-btn
            class="hide"
            label="Filter"
            color="primary"
            dense
            flat
            icon="sort"
            @click="right = !right"
          />
          <div class="row flex items-center q-my-lg">
            <div class="col-9 q-ma-xs">
              <q-input
                v-model="searchQuery"
                debounce="500"
                filled
                placeholder="Search Qbanks..."
                @keyup="handleNavigationWithKeys($event)"
              >
                <template v-slot:append>
                  <q-icon name="search" />
                </template>
              </q-input>
            </div>
            <div class="col-2">
              <q-btn color="secondary" label="Search" @click="querySearch()" />
            </div>
          </div>
          <div
            class="search-suggestions-container"
            style="z-index: 1;"
            v-show="searchQuery.length>2 &&  searchSuggestionResults.length>0 && showSuggestionBox"
          >
            <div
              v-for="(r,ind) in searchSuggestionResults"
              :key="r.id"
              class="result"
              :class="{'active-item': currentItem === ind}"
            >
              <p class="search-suggestion" v-if="r.type!='qbank'" @click="applyKeywordOnSearch(r)">
                <i class="fa fa-search icon"></i>
                <span class="keyword" v-html="highlight(r.name)"></span>
              </p>

              <p class="search-suggestion" v-else @click="applyKeywordOnSearch(r)">
                <img :src="'/storage/qbank/s/'+r.image" alt class="image" />
                <span class="keyword" v-html="highlight(r.name)"></span>
              </p>
            </div>
            <!-- <div
             v-if="searchSuggestionResults.length==0"
              class="result"
            >
              <p
                class="search-suggestion"
              >
                <span class="keyword" style="text-align:center;width:100%;">No Results Found...</span>
              </p>
            </div>-->
          </div>
          <div class="text-h5 q-pb-md">{{headerMsg}}</div>
          <div v-if="appliedFilters.length>0">
            <div class="text-h6 text-grey-6 q-pb-md flex justify-between">
              <span>Applied Filters:</span>
              <q-btn dense size="sm" color="primary" @click="clearFilters()">Clear Filter</q-btn>
            </div>
            <q-chip
              v-for="(tag,index) in appliedFilters"
              :key="tag.id"
              outline
              removable
              v-model="appliedFilters[index].show"
              @remove="removeFilter(tag,index)"
              color="primary"
              text-color="white"
            >{{tag.name}}</q-chip>
          </div>
          <div v-if="loading">
            <div class="q-pa-md row items-start q-gutter-lg flex-center">
              <q-card class="my-card bg-grey-1" v-for="cards in 6" :key="cards">
                <q-item>
                  <q-item-section>
                    <q-item-label>
                      <q-skeleton type="text" />
                    </q-item-label>
                    <q-item-label caption>
                      <q-skeleton type="text" />
                    </q-item-label>
                  </q-item-section>
                </q-item>

                <q-skeleton height="280px" square />

                <q-card-actions align="center" class="q-gutter-md">
                  <q-skeleton type="QBtn" />
                  <q-skeleton type="QBtn" />
                </q-card-actions>
              </q-card>
            </div>
          </div>
          <div class="q-pa-sm row items-start q-gutter-lg flex-center" v-else>
            <q-card class="hover-fx my-card bg-grey-1" v-for="(qb) in qbankList" :key="qb.id">
              <img width="265px" height="95px" :src="storageUrl+'qbank/l/'+qb.image" />

              <q-card-section>
                <div class="text-h6 text-uppercase" style="line-height:1;width: 256px;">{{qb.name}}</div>
              </q-card-section>

              <q-card-section class="q-pt-none q-pl-none">
                <p style="font-size: 14px;">
                  <span class="qbank-key-feature" v-html="qb.short_key_feature"></span>
                </p>
                <div class="text-h6 text-center">
                  US $
                  <span
                    class="text-strike"
                    v-if="qb.qbank_subscrip.length>0"
                  >{{qb.qbank_subscrip[0].actual_price}}</span>
                  <span
                    style="color:#d10000;font-size: 24px;"
                    v-if="qb.qbank_subscrip.length>0"
                  >{{qb.qbank_subscrip[0].actual_price-qb.qbank_subscrip[0].discount_price}}</span>
                  <span v-show="qb.qbank_subscrip.length==0">0</span>
                </div>
                <div
                  class="text-caption text-center"
                  style="color:#d10000;"
                  v-if="qb.qbank_subscrip.length>0"
                >( {{qb.qbank_subscrip[0].period.name}} subscription )</div>
              </q-card-section>
              <q-card-section class="row flex flex-center q-gutter-xs">
                <q-btn dense color="primary" label="More Details" :to="'/qbank/'+qb.slug" />
                <q-btn dense color="secondary" label="Free Trial" @click="freeTrial(qb.id)" />
              </q-card-section>
            </q-card>
            <q-card class="hover-fx bg-grey-1 empty-result-card" v-if="qbankList.length==0">
              <q-card-section class="flex flex-center q-gutter-xs">
                <p v-if="searchQuery">Sorry, we couldn't find any results for "{{searchQuery}}"</p>
                <p v-else>Sorry, we couldn't find any results </p>
              </q-card-section>
            </q-card>
          </div>
          <q-card>
            <q-card-section class="q-mt-lg">
              <div class="q-pa-xs flex flex-center">
                <q-pagination
                  v-model="currentPage"
                  :max="pagesCount"
                  input
                  input-class="text-orange-10"
                  @input="handleCurrentChange"
                />
              </div>
            </q-card-section>
          </q-card>
        </div>
      </div>
    </div>

    <q-drawer v-model="right" side="right">
      <div class="full-width bg-white">
        <!-- <search-filters :searchFilter="searchFilter" /> -->
      </div>
    </q-drawer>
  </div>
</template>

<script>
import { skeleton } from "../mixins/SkeletonMixin.js";
import { freeTrialQbank } from "../mixins/FreeTrialQbank";
import { loader } from "../mixins/LoaderMixin.js";
import { mapGetters } from "vuex";
export default {
  mixins: [skeleton, loader, freeTrialQbank],
  data() {
    return {
      qbankList: [],
      currentPage: 1,
      pageSize: 6,
      pagesCount: 0,
      baseSearchUrl: `/seach-qbanks/`,
      searchform: {
        search: {
          q: "",
          id: 0,
          type: "default",
        },
        exam: "",
        speciality: "",
        plans: [],
      },
      appliedFilters: [],
      headerMsg: "Showing Qbanks",
      searchQuery: "",
      searchSuggestionResults: [],
      showSuggestionBox: false,
      currentItem: -1,
      currentItemData: null,
      loginMode: true,
      selectedQbId: 0,
      right: false,
    };
  },
  components: {
    "search-filters": () => import("components/SearchFilters.vue"),
  },
  mounted() {
    this.fetchQbanks(this.baseSearchUrl + this.pageSize, this.searchform);
    if (this.$route.query) {
      if (this.$route.query.exam) {
        this.searchform.exam = this.$route.query.exam;
      }
    }
  },
  computed: {
    ...mapGetters("auth", ["isLoggedIn"])
  },
  methods: {
    highlight(content) {
      return content.replace(new RegExp(this.searchQuery, "gi"), (match) => {
        return '<span style="font-weight:900;">' + match + "</span>";
      });
    },
    handleNavigationWithKeys: function (event) {
      switch (event.key) {
        case "ArrowDown":
          if (this.searchSuggestionResults.length == 0) {
            break;
          }
          if (this.currentItem < this.searchSuggestionResults.length - 1) {
            this.currentItem++;
          } else {
            this.currentItem = 0;
          }
          this.currentItemData = this.searchSuggestionResults[this.currentItem];
          this.searchQuery = this.searchSuggestionResults[
            this.currentItem
          ].name;
          break;

        case "ArrowUp":
          if (this.searchSuggestionResults.length == 0) {
            break;
          }
          if (this.currentItem > 0) {
            this.currentItem--;
          } else {
            this.currentItem = this.searchSuggestionResults.length - 1;
          }
          this.currentItemData = this.searchSuggestionResults[this.currentItem];
          this.searchQuery = this.searchSuggestionResults[
            this.currentItem
          ].name;
          break;

        case "Enter":
          this.querySearch();
          this.currentItem = -1;
          break;
        default:
          this.fetchQbankSuggestionsByQuery();
      }
    },

    querySearch: function () {
      this.showSuggestionBox = false;
      this.searchform.search.q = this.searchQuery;
      if (this.currentItemData) {
        if (this.currentItemData.type == "qbank") {
          this.searchform.search.type = "qbank";
          this.searchform.search.id = this.currentItemData.qbank_id;
          this.currentItemData = null;
        } else {
          this.searchform.search.type = "default";
          this.searchform.search.id = 0;
        }
      } else {
        this.searchform.search.type = "default";
        this.searchform.search.id = 0;
      }
      if (this.searchform.exam) {
        this.appliedFilters = [];
        this.searchform.exam = "";
      } else {
        this.applyFilters();
      }
    },
    applyKeywordOnSearch: function (item) {
      this.currentItemData = item;
      this.searchQuery = item.name;
      this.querySearch();
    },

    clearFilters: function () {
      window.location.reload(true);
    },
    removeFilter: function (tag, index) {
      this.appliedFilters.splice(index, 1);
      switch (tag.type) {
        case "exam":
          this.searchform.exam = "";
          break;
        case "speciality":
          this.searchform.speciality = "";
          break;
        case "plan":
          this.searchform.plans = this.searchform.plans.filter((e) => {
            return e != tag.id;
          });

         this.$refs.filter.tooglePlanSelection(false,tag.id,tag.index);

          break;

        default:
          console.log("something went wrong");
      }
    },
    fetchQbanks: function (url, filters) {
      if (!url) {
        url = this.baseSearchUrl + this.pageSize;
      }
      this.showSkeletonLoader();
      this.showSuggestionBox = false;
      let t = this;
      axios
        .post(url, filters)
        .then((response) => {
          console.log(response.data);
          t.qbankList = [];
          if (this.searchform.search.q != "") {
            this.headerMsg = "Showing Qbanks For " + this.searchform.search.q;
          } else {
            this.headerMsg = "Showing Qbanks";
          }
          t.qbankList = response.data.data;
          t.currentPage = response.data.current_page;
          t.pagesCount = response.data.last_page;
          this.hideSkeletonLoader();
        })
        .catch((e) => {
          this.hideSkeletonLoader();
        });
    },

    handleCurrentChange(val) {
      let url = this.baseSearchUrl + this.pageSize + `?page=${val}`;
      this.applyFilters(url);
    },
    applyFilters: function (url = null) {
      if (!url) {
        url = this.baseSearchUrl + this.pageSize;
      }
      let filters = {
        exam: this.searchform.exam,
        speciality: this.searchform.speciality,
        plans: this.searchform.plans,
        search: this.searchform.search,
      };

      if (this.searchform.speciality != "") {
        let item = this.$refs.filter.specialities.find((el) => {
          return el.id == filters.speciality;
        });
        if (item) {
          filters.speciality = item.name;
        }
      }
      this.fetchQbanks(url, filters);
    },
    fetchQbankSuggestionsByQuery: function () {
      this.showSuggestionBox = false;
      if (this.searchQuery.length > 2) {
        axios
          .get("/show-qbanks-suggestions/" + this.searchQuery)
          .then((response) => {
            this.searchSuggestionResults = [];
            this.showSuggestionBox = true;
            this.searchSuggestionResults = response.data;
            response.data.forEach((e, index) => {
              if (e.qbank.length > 0) {
                this.searchSuggestionResults.push({
                  tag_id: e.id,
                  id: e.id + "t",
                  qbank_id: e.qbank[0].id,
                  name: e.qbank[0].name,
                  image: e.qbank[0].image,
                  type: "qbank",
                });
              }
            });
          });
      } else if (this.searchQuery.length == 0) {
        this.searchform.search.q = "";
        this.fetchQbanks(this.baseSearchUrl + this.pageSize, this.searchform);
      }
    },
    removePlanFromFilters(plan) {
      this.searchform.plans = this.searchform.plans.filter((e) => {
        return e != plan;
      });

      this.appliedFilters = this.appliedFilters.filter((e) => {
        return e.id != plan && e.type == "plan";
      });
    },
  },
  watch: {
    "searchform.exam": function (e) {
      if (e == "") {
        this.applyFilters();
        return;
      }

      this.searchQuery = "";
      this.searchform.search.q = "";
      this.searchform.search.id = 0;
      this.searchform.search.type = "default";
      this.appliedFilters = this.appliedFilters.filter((el) => {
        return el.id != "exam" && el.type != "exam" && el.type != "speciality";
      });

      this.appliedFilters.push({
        id: "exam",
        name: e,
        type: "exam",
        show:true
      });
      this.searchform.speciality = "";
     this.$refs.filter.specialities = [];
      this.applyFilters();
      this.$refs.filter.fetchExamsSpecialities(e);
    },
    "searchform.speciality": function (e) {
      if (e == "") {
        this.applyFilters();
        return;
      }
      
      this.appliedFilters = this.appliedFilters.filter((el) => {
        return el.id != "spc" && el.type != "speciality";
      });
      if (this.searchform.speciality != "") {
        let item = this.$refs.filter.specialities.find((el) => {
          return el.id == e;
        });
        if (item) {
          this.appliedFilters.push({
            id: "spc",
            name: item.name,
            type: "speciality",
            show:true
          });
        }
      }
      this.applyFilters();
    },
    "searchform.plans": function (e) {
      this.applyFilters();
    },
  },
};
</script>

<style lang="css" scoped>
.empty-result-card {
  width: 100%;
  font-weight: bold;
}
.search-suggestions-container {
  min-height: 3%;
  width: 55%;
  position: absolute;
  margin: 4px;
  top: 6%;
  background-color: #ffffff;
  border: 1px solid #ccc;
  border-top-color: #d9d9d9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  cursor: default;
}

.search-suggestion {
  display: flex;
  justify-content: flex-start;
  margin: 5px;
  padding: 5px;
}

.search-suggestion > .icon {
  color: #cacbcc;
  margin-right: 22px;
}

.search-suggestion > .image {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.search-suggestion > .keyword {
  line-height: 1;
}

.result:hover {
  color: #007791;
  background-color: #f2f3f5;
  cursor: pointer;
}

.active-item {
  color: #007791;
  background-color: #f2f3f5;
  cursor: pointer;
}
.hide {
  display: none;
}
.my-card {
  width: 100%;
  max-width: 265px;
}
.show {
  display: inline;
}

.hover-fx {
  transition: all 0.3s ease-out;
}

.hover-fx:hover {
  box-shadow: 0 7px 9px -4px rgba(0, 0, 0, 0.2),
    0 14px 21px 2px rgba(0, 0, 0, 0.14), 0 5px 26px 4px rgba(0, 0, 0, 0.12);
  transition: all 0.3s ease-in;
}

a {
  text-decoration: none;
  color: #04b1ed;
  font-weight: 400;
}

@media only screen and (min-width: 0px) and (max-width: 900px) {
  .hide {
    display: inline;
  }

  .show {
    display: none;
  }
  .search-suggestions-container {
    width: 69%;
    top: 3%;
  }
}
</style>
