<template>
  <div class="ais-col-filter w-full" 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"
    >
  <!--    <div class="relative bg-gray-50 divide-y divide-ui-gray-100 gap-1 flex flex-col">-->
        <div class="grid gap-1 py-1 px-2 max-h-[25rem] overflow-y-auto whitespace-nowrap">
          <AisCheckbox v-model="allSelected" size="sm" @change="selectAll">All</AisCheckbox>
          <AisCheckboxGroup v-model="selected"
                            :options="options"
                            name="columnFilter"
                            display="grid"
                            gap="gap-1"
                            size="sm"
                            class="font-normal"
          ></AisCheckboxGroup>
        </div>
  <!--      <div class="sticky -bottom-px shadow-top bg-gray-200 flex items-center h-10 p-2">-->
  <!--        <AisButton size="xs" variant="default" block @click="applyFilter">Apply</AisButton>-->
  <!--      </div>-->
  <!--    </div>-->
    </AisMenu>
  </div>
</template>

<script setup>
  import { computed, onMounted, provide, ref, watch } from "vue";
  import AisMenu from "@/components/menu/AisMenu.vue";
  import AisCheckbox from "@/components/checkbox/AisCheckbox.vue";
  import AisCheckboxGroup from "@/components/checkbox-group/AisCheckboxGroup.vue";
  import AisButton from "@/components/button/AisButton.vue";
  import { getDisplayValue } from "@/util/table-util";
  import { faFilter } from '@fortawesome/free-solid-svg-icons'
  import { library } from "@fortawesome/fontawesome-svg-core";
  library.add(faFilter)

  const menu = ref()
  const allSelected = ref(true)
  const selected = ref([])

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

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

  const options = computed(() => {
    let opts = [];

    if(props.items && props.items.length > 0) {
      if(props.field)
        opts = [...new Set(props.items.map(item => getDisplayValue(item, props.field) || '00000000'))];

      if(!opts || opts.length === 0)
        opts = [...new Set(props.items)];
    }

    opts.sort()

    const result = opts.reduce((r, o) => {
                          if(o === '00000000')
                            r.push({ value: '', label: '(blanks)' })
                          else
                            r.push({ value: String(o), label: o })

                          return r
                        }, [])

    return result
  })

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

    if(!allSelected.value && selected.value.length > 0)
      classes.push('!text-blue-500')
    // else if (props.dark)
    //   classes.push('text-primary')

    return classes.join(' ')
  })


  const selectAll = () => {
    selected.value = allSelected.value ? options.value.map(o => o?.hasOwnProperty('value') ? o.value : o) : []
  }

  // const applyFilter = () => { console.log(`applyFIlter: selected=[${selected.value}]`); emit('update:modelValue', selected.value) }

  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
  })

  onMounted(() => {
    selected.value = options.value.map(o => o?.hasOwnProperty('value') ? o.value : o)
  })

  watch(() => selected.value, (newVal) => {
    // console.log(`watch.value: newVal.length=[${newVal.length}], o.l=[${options.value.length}], eq=[${newVal.length === options.value.length}]`)
    allSelected.value = newVal.length > 0 && newVal.length === options.value.length
    emit('update:modelValue', allSelected.value ? [] : selected.value)
  })
  watch(() => props.modelValue, (newVal, oldVal) => {
    // console.log(`atcf.mv.watch: oldVal=[${oldVal}], newVal=[${newVal}], as=[${allSelected.value}], nv.empty=[${newVal.length}]`)
    if(!(allSelected.value && newVal?.length === 0))
      selected.value = props.modelValue
  })

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

</script>