<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<!-- eslint-disable vue/no-deprecated-dollar-listeners-api -->
<template>
  <VDataTable
    ref="dynamicDataTable"
    class="dynamic-table"
    :items="items"
    :headers="allHeaders"
    :itemsPerPage.sync="itemsPerPage"
    disableFiltering
    :footerProps="{
      itemsPerPageText: $t('Rows per page:'),
      itemsPerPageOptions: itemsPerPageOptions,
    }"
    :noResultsText="$t('No matching records found')"
    :noDataText="$t('No data available')"
    :mobileBreakpoint="disableMobileView ? 0 : 600"
    v-bind="$attrs"
    :fixedHeader="!isBrokenIOS"
    @update:page="scrollPageTop"
    v-on="$listeners"
  >
    <template v-for="tableHeader in headers" #[`item.${tableHeader.value}`]="{ item, header }">
      <slot :name="[`${tableHeader.id || tableHeader.value}`]" :item="item" :header="header">
        <Component
          :is="getRendererFor(tableHeader)"
          :key="tableHeader.field"
          :item="item"
          :value="header.value"
          v-bind="header.renderer && header.renderer.props ? header.renderer.props : {}"
          v-on="header.renderer && header.renderer.on ? header.renderer.on : {}"
        />
      </slot>
    </template>

    <template #[`item.action`]="{ item }">
      <slot name="action" :item="item">
        <VBtn fab xSmall depressed>
          <VIcon class="ma-0">fa fa-chevron-right</VIcon>
        </VBtn>
      </slot>
    </template>

    <template v-for="(_, slot) in slots" #[slot]="scope">
      <slot :name="slot" v-bind="scope" />
    </template>

    <template #footer.page-text="footerItems">
      {{ footerItems.pageStart }} - {{ footerItems.pageStop }} {{ $t('of') }} {{ footerItems.itemsLength }}
    </template>
  </VDataTable>
</template>

<script>
import ButtonRenderer from './Renderers/ButtonRenderer'
import CheckCircleRenderer from './Renderers/CheckCircleRenderer'
import RouterLinkRenderer from './Renderers/RouterLinkRenderer'
import TextRenderer from './Renderers/TextRenderer'
import { PLATFORM } from '@pitcher/core/src/platform'
import { computed, defineComponent, ref } from '@vue/composition-api'
import { getRendererFor } from './Renderers/helpers'

export default defineComponent({
  name: 'PDynamicTable',
  components: { CheckCircleRenderer, TextRenderer, RouterLinkRenderer, ButtonRenderer },
  inheritAttrs: false,
  props: {
    items: { type: Array, required: true },
    headers: { type: Array, required: true },
    defaultItemsPerPage: { type: Number, default: 50 },
    hasDefaultAction: { type: Boolean, default: true },
    disableMobileView: { type: Boolean, default: false },
  },
  setup(props, ctx) {
    const itemsPerPage = ref(props.defaultItemsPerPage)
    const allHeaders = computed(() => {
      if (props.hasDefaultAction) {
        return [
          ...props.headers,
          {
            text: '',
            value: 'action',
            sortable: false,
          },
        ]
      } else {
        return props.headers
      }
    })

    const itemsPerPageOptions = computed(() => {
      const defaultItemsPerPageOptions = [50, 100, 250]

      if (defaultItemsPerPageOptions.includes(props.defaultItemsPerPage)) return defaultItemsPerPageOptions

      defaultItemsPerPageOptions.push(props.defaultItemsPerPage)

      return defaultItemsPerPageOptions
    })

    function scrollPageTop() {
      ctx.root.$vuetify.goTo(ctx.refs.dynamicDataTable, {
        offset: 0,
        container: '.v-data-table__wrapper',
      })
    }

    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
    const isBrokenIOS =
      isIOSLegacyWebVIew && (iOSVersionMajor >= 16 || (iOSVersionMajor === 16 && iOSVersionMinor >= 4))

    return {
      allHeaders,
      isBrokenIOS,
      itemsPerPage,
      getRendererFor,
      scrollPageTop,
      itemsPerPageOptions,
      slots: ctx.slots,
    }
  },
})
</script>

<style lang="scss" scoped>
@import '../../styles/mixins.scss';

// Vuetify specificity override
.dynamic-table.dynamic-table.dynamic-table.dynamic-table.dynamic-table {
  display: flex;
  flex: 1;
  flex-basis: 0;
  flex-direction: column;
  min-height: 0;
  padding-left: 0;
  padding-right: 0;
  margin: $spacer * 2 0 0 0;

  @include md-and-up {
    padding-left: $spacer * 4;
    padding-right: $spacer * 4;
    margin: 0 $spacer * 4 0;
  }

  ::v-deep {
    .v-data-table__wrapper {
      overflow-y: auto;
    }

    .v-data-footer__select .v-input__append-inner {
      pointer-events: none;
    }

    @include xs-only {
      .v-data-footer {
        margin-inline-end: 0;
      }

      .v-data-footer__pagination {
        margin: 0 $spacer * 4;
      }

      .v-data-footer__select .v-select {
        margin-inline-start: $spacer * 4;
      }
    }

    .v-data-table-header {
      vertical-align: top;

      th {
        height: auto;
        padding-top: $spacer * 2;
        padding-bottom: $spacer * 2;
      }

      th.sortable .v-data-table-header__icon {
        position: absolute;
        margin-inline-start: $spacer;
      }
    }
  }
}
</style>
