<template>
  <div class="flex min-h-57 flex-col justify-between">
    <div class="flex flex-col gap-2">
      <InputText
        v-model="model.value"
        fluid
        type="search"
        placeholder="Filter&hellip;"
      />

      <div
        class="flex justify-center rounded-md border border-primary bg-primary px-2 py-1
          text-primary-contrast transition-colors duration-200 select-none"
        :class="[
          hovered && 'border-primary-emphasis bg-primary-emphasis',
          activated && 'border-primary-emphasis-alt bg-primary-emphasis-alt'
        ]"
      >
        {{ badge }}
      </div>

      <ButtonGroup class="flex flex-row">
        <template v-for="{ name, icon, matchMode } in matchModes">
          <Button
            v-if="!isCurrentMatchMode(matchMode)"
            size="sm"
            variant="outlined"
            class="grow px-0! py-1.5! hover:bg-primary/15"
            @click="changeMatchMode(matchMode)"
            @pointerdown="activate()"
            @pointerup="deactivate()"
            @pointerenter="hover(name)"
            @pointerleave="unhover()"
          >
            <Icon :name="icon" />
          </Button>

          <div
            v-else
            class="relative inline-flex grow items-center justify-center gap-2
              overflow-hidden rounded-md border border-primary-400 bg-primary-100 px-0 py-1.5
              text-sm text-primary transition-colors duration-200 select-none
              dark:border-primary-500 dark:bg-primary/15"
          >
            <Icon :name="icon" />
          </div>
        </template>
      </ButtonGroup>
    </div>

    <Button
      class="py-0.5!"
      variant="outlined"
      size="small"
      fluid
      :disabled="!hasFilterFor(props.field)"
      @click="resetFilterFor(props.field)"
    >
      Reset
    </Button>
  </div>
</template>

<script setup>
const model = defineModel()

const props = defineProps({
  field: {
    type: String,
    required: true
  }
})

const { hasFilterFor, resetFilterFor } = useFiltersStore()

const badge = ref()
const hovered = ref(false)
const activated = ref(false)

watch(
  () => model.value.matchMode,
  (matchMode) => {
    badge.value = nameFromMatchMode(matchMode)
    hovered.value = false
  },
  { immediate: true }
)

function isCurrentMatchMode(matchMode) {
  return matchMode === model.value.matchMode
}

function hover(name) {
  hovered.value = true
  badge.value = name
}

function unhover() {
  hovered.value = false
  badge.value = nameFromMatchMode(model.value.matchMode)
}

function activate() {
  activated.value = true
}

function deactivate() {
  activated.value = false
}

function changeMatchMode(matchMode) {
  model.value.matchMode = matchMode
  deactivate()
}
</script>

<style scoped></style>
