<template>
  <div class="ivyforms-table-bulk-header">
    <IvyCheckbox
      type="checkmark"
      size="s"
      :model-value="checkboxValue"
      :indeterminate="someSelected && !allSelected"
      :disabled="loading"
      class="ivyforms-ml-6"
      @update:model-value="onCheckboxChange"
    >
      <slot></slot>
    </IvyCheckbox>
    <IvyButtonAction
      v-if="primaryAction"
      :priority="primaryAction.danger ? 'danger' : 'tertiary'"
      size="xs"
      :disabled="loading || !selectedIds.length"
      @click="primaryAction.onClick"
    >
      {{ primaryAction.label }}
    </IvyButtonAction>
    <IvyButtonAction
      v-if="menuActions && menuActions.length"
      ref="bulkMenuButtonRef"
      icon-only
      icon-start="context-menu-dot"
      size="xs"
      type="fill"
      priority="tertiary"
      class="ivyforms-flex ivyforms-align-items-center ivyforms-gap-8 ivyforms-ml-8"
      :disabled="loading || !selectedIds.length"
      :aria-label="getLabel('more_actions')"
      @click="openBulkMenu"
    >
    </IvyButtonAction>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import IvyButtonAction from '@/views/_components/button/IvyButtonAction.vue'
import type { ComponentPublicInstance } from 'vue'
import IvyCheckbox from '@/views/_components/checkbox/IvyCheckbox.vue'
import { useLabels } from '@/composables/useLabels.ts'
import { useContextMenuStore } from '@/stores/contextMenuStore.ts'
import type { ContextMenuAction } from '@/views/_components/context-menu/context-menu-action'

export interface BulkPrimaryAction {
  label: string
  danger?: boolean
  onClick: () => void
}

const { getLabel } = useLabels()
const contextMenuStore = useContextMenuStore()
const bulkMenuButtonRef = ref<ComponentPublicInstance | null>(null)

const props = defineProps<{
  selectedIds: Array<number | string>
  loading?: boolean
  primaryAction?: BulkPrimaryAction
  menuActions?: ContextMenuAction[]
  allSelected?: boolean
  someSelected?: boolean
}>()

const emit = defineEmits<{
  (e: 'unselect-all'): void
  (e: 'toggle-all'): void
}>()

const checkboxValue = computed(() => Boolean(props.allSelected))

const onCheckboxChange = (value: boolean) => {
  if (props.loading) return
  if (!value) {
    emit('unselect-all')
  } else {
    emit('toggle-all')
  }
}

const openBulkMenu = () => {
  if (props.loading) return
  if (!props.selectedIds.length || !props.menuActions?.length) return
  contextMenuStore.openContextMenu({
    actions: props.menuActions,
    contextMenuButtonRef: bulkMenuButtonRef.value,
  })
}
</script>

<style lang="scss">
.ivyforms-table-bulk-header {
  display: flex;
  height: 48px;
  padding: 0 16px 0 8px;
  align-items: center;
  align-self: stretch;
  background: var(--map-ground-level-1-foreground);
}
</style>
