<template>
  <div class="d-flex align-center justify-center" :style="customFilterStyle">
    <VTextField
      v-model="searchString"
      outlined
      dense
      hideDetails
      :label="$t('Search')"
      prependInnerIcon="fal fa-search"
      width="200"
      clearable
      class="me-2"
    />
    <VMenu v-if="showCustomAccountContactFilters" offsetY :closeOnContentClick="false">
      <template #activator="{ on, attrs }">
        <VBadge dot top bottom color="green lighten-1" offsetX="17" offsetY="18" :value="hasFilterSelected">
          <PButton
            :disabled="filters.length === 0"
            small
            fab
            v-bind="attrs"
            :isActive="hasFilterSelected"
            class="me-2"
            v-on="on"
          >
            <VIcon small>far fa-filter</VIcon>
          </PButton>
        </VBadge>
      </template>
      <VCard :width="480" maxHeight="70vh">
        <VCardText>
          <div class="d-flex pa-2 justify-end align-center">
            <span v-if="selectedFilter && selectedFilter.name" class="text-caption me-2">
              {{ selectedFilter.name }}
            </span>
            <PButton v-if="enableSaveLoadFilters" :disabled="!hasFilterSelected" @click="toggleDialog()">
              {{ $t('Save') }}
            </PButton>
            <VMenu v-if="enableSaveLoadFilters" offsetY :closeOnClick="true" :closeOnContentClick="false">
              <template #activator="{ on, attrs }">
                <PButton class="ms-2" :disabled="savedFilters.length === 0" v-bind="attrs" v-on="on">
                  {{ $t('Load') }}
                </PButton>
              </template>
              <VList :width="400">
                <VListItem v-for="(filter, index) in paginatedSavedFilters" :key="index" @click="applyFilter(filter)">
                  <VListItemContent>
                    <VListItemTitle>{{ filter.name }}</VListItemTitle>
                    <VListItemSubtitle>{{ new Date(filter.timestamp).toLocaleString() }}</VListItemSubtitle>
                  </VListItemContent>
                  <VListItemAction>
                    <VIcon size="20" @click.stop="deleteFilter(filter)">
                      far fa-trash-alt
                    </VIcon>
                  </VListItemAction>
                </VListItem>
              </VList>
              <VPagination
                v-if="pageCount > 1"
                v-model="currentPage"
                totalVisible="9"
                :length="pageCount"
                class="mt-3"
              />
            </VMenu>
            <PButton
              class="ms-2"
              :disabled="!hasFilterSelected"
              @click="
                resetAppliedFilter()
                resetFilters()
              "
            >
              {{ $t('Clear All') }}
            </PButton>
          </div>

          <div v-for="(filter, index) in filters" :key="index" class="pa-2">
            <CustomFilter :filter="filter" :type="type" :applyMargin="applyMargin" />
          </div>
        </VCardText>
      </VCard>
      <VDialog v-model="isSaveDialogVisible" persistent maxWidth="640px">
        <VCard :width="480">
          <VCardTitle>
            {{ $t('Save filter') }}
          </VCardTitle>
          <VCardText>
            <VForm v-model="valid">
              <VTextField v-model="newFilterName" :label="$t('Filter name')" :rules="filterNameRules" required />
            </VForm>
          </VCardText>
          <VCardActions>
            <VBtn color="secondary" class="mr-4" @click="toggleDialog()">
              {{ $t('Cancel') }}
            </VBtn>
            <VBtn
              :disabled="!valid"
              color="primary"
              class="mr-4"
              @click="
                saveFilters()
                toggleDialog()
              "
            >
              {{ $t('Save') }}
            </VBtn>
            <VBtn
              v-if="selectedFilter && selectedFilter.timestamp"
              :disabled="!valid || doesFilterNameExist"
              color="primary"
              class="mr-4"
              @click="
                saveFilters(true)
                toggleDialog()
              "
            >
              {{ $t('Save As') }}
            </VBtn>
          </VCardActions>
        </VCard>
      </VDialog>
    </VMenu>
  </div>
</template>

<script>
import CustomFilter from './CustomFilter'
import PButton from '../../PButton/PButton'
import { computed, defineComponent, onMounted, ref } from '@vue/composition-api'
import { useCustomFiltersContext } from '@pitcher/core'
import { useFilterSaveLogic } from '../../../utils/filter-storage'

export default defineComponent({
  name: 'CustomAccountContactFilters',
  components: { CustomFilter, PButton },
  props: {
    width: {
      type: [Number, String],
      required: false,
    },
    type: {
      type: String,
      required: true,
    },
    showCustomAccountContactFilters: {
      type: Boolean,
      default: true,
    },
    applyMargin: {
      type: Boolean,
      required: false,
      default: false,
    },
    enableSaveLoadFilters: {
      type: Boolean,
      default: false,
    },
    reverseFilterOrder: {
      type: Boolean,
      default: false,
    },
  },
  setup(props) {
    const { filters, resetFilters, searchString, hasFilterSelected, selectedFilters } = useCustomFiltersContext(
      props.type
    )

    const valid = ref(false)
    const filterNameRules = [(v) => !!v || 'E-mail is required']

    const isSaveDialogVisible = ref(false)

    const {
      selectedFilter,
      savedFilters,
      doesFilterNameExist,
      loadFilters,
      selectAndApplyFilter,
      deleteFilter,
      resetAppliedFilter,
      saveFilter,
      newFilterName,
      pageCount,
      currentPage,
      paginatedSavedFilters,
    } = useFilterSaveLogic(props.type, resetFilters)

    const customFilterStyle = computed(() =>
      props.width ? { width: typeof props.width === 'number' ? `${props.width}px` : props.width } : {}
    )

    const orderedFilters = computed(() => {
      return props.reverseFilterOrder ? [...filters.value].reverse() : filters.value
    })

    const reduceSelected = () => {
      const filtersToSave = {}

      for (const key in selectedFilters.value) {
        if (Array.isArray(selectedFilters.value[key]) && selectedFilters.value[key].length > 0) {
          filtersToSave[key] = selectedFilters.value[key]
        }
      }

      return filtersToSave
    }

    const saveFilters = (isSaveAs) => {
      saveFilter(reduceSelected(), isSaveAs)
    }

    const toggleDialog = () => {
      isSaveDialogVisible.value = !isSaveDialogVisible.value
    }

    const applyFilter = (filter) => {
      selectAndApplyFilter(filter, selectedFilters)
    }

    onMounted(async () => {
      if (props.enableSaveLoadFilters) {
        await loadFilters()
      }
    })

    return {
      filters: orderedFilters,
      resetFilters,
      searchString,
      hasFilterSelected,
      customFilterStyle,
      selectedFilter,
      savedFilters,
      applyFilter,
      isSaveDialogVisible,
      saveFilters,
      toggleDialog,
      valid,
      filterNameRules,
      doesFilterNameExist,
      newFilterName,
      deleteFilter,
      resetAppliedFilter,
      pageCount,
      currentPage,
      paginatedSavedFilters,
    }
  },
})
</script>

<style lang="scss" scoped>
.v-card {
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
