<template>
  <v-btn
      class="mr-4 theme-primary"
      :class="hasOtherActions ? 'pr-0' : ''"
      @click="submitAction(mainAction)"
      ref="mainBtn"
      :disabled="validationPending"
  >

    {{ $t(mainAction) }}

    <v-divider class="ml-3" :vertical="true" v-if="hasOtherActions"></v-divider>

    <v-menu
      :top="dropDirection === 'top'"
      offset-y
      left
      v-if="hasOtherActions"
      :nudge-top="dropDirection === 'top' ? 6 : 0"
      :nudge-bottom="dropDirection === 'bottom' ? 6 : 0"
    >
      <template #activator="{ on, attrs }">
        <v-toolbar-title v-on="on">
          <v-icon class="pl-3 pr-3">
            {{ dropDirection === 'top' ? 'fa fa-caret-up' : 'fa fa-caret-down'}}
          </v-icon>
        </v-toolbar-title>
      </template>
      <v-list
        :min-width="menuSize"
      >
        <v-list-item
          dense
          v-for="(action, index) in actions"
          :key="index"
          class="subAction"
          v-if="index > 0"
        >
          <v-list-item-title v-text="$t(action)" @click="submitAction(action)" />
        </v-list-item>
      </v-list>
    </v-menu>
  </v-btn>
</template>

<script setup lang="ts">
import {computed, ref} from "@vue/reactivity";
import type {ComputedRef, Ref} from "@vue/reactivity";

const props = defineProps({
  actions: {
    type: Array,
    required: true
  },
  dropDirection: {
    type: String,
    required: false,
    default:'bottom'
  },
  validationPending: {
    type: Boolean,
    required: false,
    default: false
  }
})

const emit = defineEmits(['submit'])

const mainBtn: Ref = ref(null)
const menuSize = computed(()=>{
  // Btn size + 40px de padding
  return mainBtn.value?.$el.clientWidth + 40
})

const submitAction = (action: string) => {
  emit('submit', action)
}

const mainAction: ComputedRef<string> = computed(()=>{
  return props.actions[0] as string
})

const hasOtherActions: ComputedRef<boolean> = computed(()=>{
  return props.actions.length > 1
})

</script>

<style scoped>
.v-list-item--dense{
  min-height: 25px;
}
.subAction{
  cursor: pointer;
}
</style>
