<template>
  <v-btn
    ref="mainBtn"
    class="submit-btn theme-primary"
    :class="hasOtherActions ? 'pr-0' : ''"
    :disabled="validationPending"
    @click="submitAction(mainAction)"
  >
    {{ $t(mainAction) }}

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

    <v-menu
      v-if="hasOtherActions"
      :top="dropDirection === 'top'"
      offset-y
      left
      :nudge-top="dropDirection === 'top' ? 6 : 0"
      :nudge-bottom="dropDirection === 'bottom' ? 6 : 0"
    >
      <template #activator="{ on }">
        <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
          v-for="(action, index) in otherActions"
          :key="index"
          dense
          class="subAction"
        >
          <v-list-item-title
            @click="submitAction(action)"
          >
            {{ $t(action) }}
          </v-list-item-title>
        </v-list-item>
      </v-list>
    </v-menu>
  </v-btn>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import type { ComputedRef, Ref } from 'vue'

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

const otherActions: ComputedRef<Array<string>> = computed(() => {
  return props.actions.filter((_, index) => index > 0) as Array<string>
})
</script>

<style scoped>
.submit-btn {
  margin-right: 12px;

  @media (max-width: 600px) {
    margin: 0;
  }
}

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