<!-- eslint-disable vue/no-deprecated-dollar-listeners-api -->
<template>
  <div class="d-contents">
    <VSheet class="ma-0 mt-2 ma-sm-4 mb-0 mb-sm-0 pa-2 pa-sm-4">
      <div class="d-flex justify-center align-center fill-width">
        <CustomAccountContactFilters
          :width="filtersWidth"
          :type="type"
          :showCustomAccountContactFilters="showCustomAccountContactFilters"
          :applyMargin="applyMargin"
          :enableSaveLoadFilters="enableSaveLoadFilters"
          :reverseFilterOrder="reverseFilterOrder"
        />

        <VSpacer />
        <slot
          name="actions"
          v-bind="{
            data,
            loading,
            searchString,
            selectedFilters,
            pageLength,
            rowCount,
            fetchOptions,
            fetchAllMatchingFilter,
            hasActiveFilter,
          }"
        />
      </div>
    </VSheet>
    <DynamicTable
      :value="selectedItems"
      :items="innerItems"
      :headers="tableHeaders"
      :loading="loading"
      :options="fetchOptions"
      :serverItemsLength="rowCount"
      :defaultItemsPerPage="defaultItemsPerPage"
      :loadingText="$t('Loading...')"
      :disableMobileView="disableMobileView"
      v-bind="$attrs"
      @update:options="fetchOptions = $event"
      v-on="$listeners"
    >
      <template v-for="(_, slot) in slots" #[slot]="scope">
        <slot
          :name="slot"
          v-bind="{
            ...scope,
            data,
            loading,
            searchString,
            selectedFilters,
            pageLength,
            rowCount,
            fetchOptions,
            fetchAllMatchingFilter,
            hasActiveFilter,
          }"
        />
      </template>
    </DynamicTable>
  </div>
</template>

<script>
import CustomAccountContactFilters from './CustomFilters/CustomAccountContactFilters'
import DynamicTable from '../PDynamicTable/PDynamicTable'
import { PLATFORM, useAccountOrContactStore, useCustomFiltersContext } from '@pitcher/core'
import { computed, defineComponent } from '@vue/composition-api'

// eslint-disable-next-line no-unused-vars
function isBrokenIOS() {
  const isIOS = PLATFORM === 'IOS'
  const isIOSLegacyWebVIew = isIOS && !window.webkit?.messageHandlers // is UIWebView

  const IOS_VERSION_REGEXP = /OS (\d+)_(\d+)/
  const iOSVersionMatch = (isIOS && navigator.userAgent.match(IOS_VERSION_REGEXP)) || []
  const iOSVersionMajor = Number(iOSVersionMatch[1] || 0)
  const iOSVersionMinor = Number(iOSVersionMatch[2] || 0)

  // UIWebView on iOS >= 16.4 has severe rendering issues, this flag is being used to decide when to mitigate them
  return isIOSLegacyWebVIew && (iOSVersionMajor >= 16 || (iOSVersionMajor === 16 && iOSVersionMinor >= 4))
}

/**
 * Pitcher Accounts Contacts Table component
 * @inherits v-data-table
 */

export default defineComponent({
  name: 'PAccountsContactsTable',
  components: { CustomAccountContactFilters, DynamicTable },
  inheritAttrs: false,
  props: {
    tableHeaders: { type: Array, required: true },
    type: {
      type: String,
      required: true,
      validator: (v) => {
        if (!['account', 'contact'].includes(v)) {
          console.error(`[Vue warn]: Validation error PAccountContactsTable!`)
          console.error(`[Vue warn]: accepted type values: contact | account`)

          return false
        }

        return true
      },
    },
    applyMargin: {
      type: Boolean,
      default: false,
    },
    value: { type: Array, required: false },
    mapSelectedItemsToData: { type: Function, required: false },
    items: { type: Array, required: false },
    filtersWidth: { type: [Number, String], required: false },
    showCustomAccountContactFilters: { type: Boolean, default: true },
    disableMobileView: { type: Boolean, default: false },
    enableSaveLoadFilters: { type: Boolean, default: false },
    reverseFilterOrder: { type: Boolean, default: false },
  },

  setup(props, ctx) {
    const {
      data,
      loading,
      selectedFilters,
      pageLength,
      rowCount,
      fetchOptions,
      fetchAllMatchingFilter,
      defaultItemsPerPage,
    } = useAccountOrContactStore(props.type)

    const { hasFilterSelected, searchString } = useCustomFiltersContext(props.type)
    const hasActiveFilter = computed(() => hasFilterSelected.value || searchString.value) // TODO move this to core package

    const innerItems = computed(() => {
      return props.items ? props.items : data.value
    })

    const selectedItems = computed(() =>
      props.mapSelectedItemsToData ? props.mapSelectedItemsToData(props.value, innerItems.value) : props.value
    )

    return {
      defaultItemsPerPage,
      innerItems,
      selectedItems,
      data,
      loading,
      searchString,
      selectedFilters,
      pageLength,
      rowCount,
      fetchOptions,
      fetchAllMatchingFilter,
      hasActiveFilter,
      slots: ctx.slots,
    }
  },
})
</script>

<style scoped>
.d-contents {
  display: contents;
}
</style>
