<template>
  <loader class="page-overview" :is-loading="isLoadingPages">
    <portal to="top-header-left">
      <search ref="search" v-model="searchInput" />
    </portal>
    <div class="pb-3 d-inline-block">
      <span class="mr-2">Type</span>
      <dropdown-menu :label="selectedFilterDisplayName || 'Alle'" class="d-inline-block position-relative bg-white border rounded">
        <button class="p-2 d-flex align-items-center dropdown-item" @click="setPageTypeFilter('')">Alle</button>
        <button
          class="p-2 d-flex align-items-center dropdown-item"
          v-for="(pageType, index) in pageTypes"
          :key="index"
          @click="setPageTypeFilter(pageType.itemName)"
        >
          <template v-if="pageType">{{ pageType.itemDisplayName }}</template>
        </button>
      </dropdown-menu>
      <button class="btn btn-link" @click="resetFilters" v-if="hasFilters">Verwijder filters</button>
    </div>
    <nested-page-table item-component="page-overview-item" :type-filter="typeFilter" :search="searchInput">
      <template v-slot:header>
        <div class="status">Status</div>
        <div class="type">Type</div>
      </template>
    </nested-page-table>
  </loader>
</template>

<script lang="ts">
import { Vue, Component, Ref } from 'vue-property-decorator';
import { namespace } from 'vuex-class';

import Loader from '../shared/loader.vue';
import Search from '../shared/search.vue';
import NestedPageTable from './nested-page-table.vue';
import { Page } from '../types/api';

const PageStore = namespace('pages');

@Component({
  name: 'PageOverview',
  components: {
    Loader,
    Search,
    NestedPageTable
  }
})
export default class PageOverview extends Vue {
  searchInput = '';
  typeFilter = '';

  @PageStore.State('isLoadingPages') readonly isLoadingPages!: Page[];
  @PageStore.Getter('pageTypesByItem') readonly pageTypes!: Page[];

  @Ref() readonly search!: Search;

  mounted() {
    const { typeFilter } = this.$route.query;

    this.typeFilter = typeFilter as string || '';
  }

  setPageTypeFilter(filter: string) {
    this.typeFilter = filter;
  }

  resetFilters() {
    this.search.clear();
    this.typeFilter = '';
  }

  get selectedFilterDisplayName() {
    return this.pageTypes.find((page) => page.itemName === this.typeFilter)?.itemDisplayName
  }

  get hasFilters() {
    return this.searchInput || this.typeFilter;
  }
}
</script>

<style lang="scss" scoped>
.status,
.type {
  padding: .5rem;
}

.status {
  flex: 0 0 20%;
}
</style>
