<template>
  <div class="ais-col-date-filter" style="text-align: inherit" ref="menu">
    <AisMenu :icon="faFilter"
             :dark="dark"
             class="z-30 cursor-pointer w-full"
             :class="dark ? 'text-white' : 'text-secondary'"
             :button-class="buttonClasses"
             :right="checkPosition"
    >
      <AisMenuItem label="In the next year" @click="inTheNextYear"></AisMenuItem>
      <AisMenuItem label="In the next year or blank" @click="inTheNextYearBlank"></AisMenuItem>
      <AisMenuItem label="In the last year" @click="inTheLastYear"></AisMenuItem>
      <AisMenuItem label="In the last year or blank" @click="inTheLastYearBlank"></AisMenuItem>
      <AisMenuDivider/>
      <AisMenuGroup label="Custom Date Values">
        <div class="grid gap-1 p-2 pt-0">
          <AisSelect v-model="filter.type" :options="options" size="sm"></AisSelect>

          <AisDatepicker v-model="filter.from" size="sm"></AisDatepicker>

          <AisDatepicker v-if="['between', 'betweenNull'].includes(filter.type)" v-model="filter.to" size="sm"></AisDatepicker>
        </div>
      </AisMenuGroup>
      <AisMenuDivider/>
      <AisMenuItem>
        <div class="grid grid-cols-2 gap-2 px-2 py-1">
          <div><AisButton size="xs" variant="default" alternate block font="sans" @click="clear">Clear</AisButton></div>
          <div><AisButton size="xs" variant="info" block font="sans" @click="apply">Apply</AisButton></div>
        </div>
      </AisMenuItem>
    </AisMenu>
  </div>
</template>

<script setup>
  import { computed, provide, ref, watch } from "vue";
  import { useNow, useDateFormat } from '@vueuse/core'
  import AisMenu from "@/components/menu/AisMenu.vue";
  import AisMenuItem from "@/components/menu/AisMenuItem.vue";
  import AisMenuGroup from "@/components/menu/AisMenuGroup.vue";
  import AisMenuDivider from "@/components/menu/AisMenuDivider.vue";
  import AisSelect from "@/components/select/AisSelect.vue";
  import AisDatepicker from "@/components/datepicker/AisDatepicker.vue";
  import AisButton from "@/components/button/AisButton.vue";
  import { faFilter } from '@fortawesome/free-solid-svg-icons'
  import { library } from "@fortawesome/fontawesome-svg-core";
  library.add(faFilter)

  const menu = ref()
  const emit = defineEmits(['update:modelValue', 'input', 'change', 'click'])

  const props = defineProps({
    modelValue: { type: Object, default: () => {} },
    items: { type: Array, default: () => [] },
    field: { type: String, default: () => '' },
    dark: { type: Boolean, default: () => '' },
  })

  const filter = ref({
    type: '',
    from: '',
    to: '',
  })

  const options = ref([
    { value: '', label: '', },
    { value: 'equals', label: 'Equals', },
    { value: 'before', label: 'Before', },
    { value: 'beforeNull', label: 'Before with blanks', },
    { value: 'after', label: 'After', },
    { value: 'afterNull', label: 'After with blanks', },
    { value: 'between', label: 'Between', },
    { value: 'betweenNull', label: 'Between with blanks', },
    { value: 'blank', label: 'blanks', },
  ])

  const buttonClasses = computed(() => {
    const classes = ['items-center gap-1 menu-bttn']

    if(filter.value && filter.value.type)
      classes.push('!text-blue-500')

    return classes.join(' ')
  })

  const localValue = computed({
    get () { return props.modelValue },
    set(val) {
      emit('update:modelValue', val)
      emit('input', val)
      emit('change', val)
    }
  })

  const checkPosition = computed(() => {
    if(menu.value) {
      const menuEl = menu.value
      const tableEl = menu.value.closest('table.ais')
      const menuLeft = menuEl?.getBoundingClientRect()?.left || 0
      const tableRight = tableEl?.getBoundingClientRect()?.right || 0
      const diff = tableRight - menuLeft

      if(tableRight > 0 && menuLeft > 0 && diff < 224) //224 is min width of menu dropdown container
        return true
    }

    return false
  })

  const inTheNextYear = () => {
    filter.value.type = 'between'
    filter.value.from = useDateFormat(useNow(), 'YYYY-MM-DD').value
    filter.value.to = getYearFromNow(1)
    apply()
  }

  const inTheNextYearBlank = () => {
    filter.value.type = 'betweenNull'
    filter.value.from = useDateFormat(useNow(), 'YYYY-MM-DD').value
    filter.value.to = getYearFromNow(1)
    apply()
  }

  const inTheLastYear = () => {
    filter.value.type = 'between'
    filter.value.from = getYearFromNow(-1)
    filter.value.to = useDateFormat(useNow(), 'YYYY-MM-DD').value
    apply()
  }

  const inTheLastYearBlank = () => {
    filter.value.type = 'betweenNull'
    filter.value.from = getYearFromNow(-1)
    filter.value.to = useDateFormat(useNow(), 'YYYY-MM-DD').value
    apply()
  }

  const getYearFromNow = (years) => {
    const today = new Date()
    return useDateFormat(today.setFullYear(today.getFullYear() + years), 'YYYY-MM-DD').value
  }

  const clear = () => {
    filter.value.type = ''
    filter.value.from = null
    filter.value.to = null
    apply()
  }

  const apply = (e) => {
    localValue.value = { ...filter.value }
    emit('click', e)
  }


  watch(() => props.modelValue, (newVal, oldVal) => {
    // console.log(`atcdf.mv.watch: oldVal=[${JSON.stringify(oldVal)}], newVal=[${JSON.stringify(newVal)}]`)
    if(newVal) {
      filter.value.type = newVal.type
      filter.value.from = newVal.from
      filter.value.to = newVal.to
    } else {
      clear()
    }
  })

  provide( 'navMargin', computed(() => 'mt-[3px]') )
</script>

<script>
export default {
  name: "AisTableColumnDateFilter",
}
</script>