<template>
  <div
    ref="splitContainer"
    :class="containerClasses"
    class="vc-split-button"
  >
    <slot>
      <button
        :disabled="disabled"
        class="vc-split-button__button"
        @click="handleClick"
      >
        <i
          :class="selectedValue?.icon"
          class="content-icon"
        />
        {{ selectedValue?.label }}
      </button>
    </slot>
    <VcPopover
      :click-outside-handler="closeDropdown"
      :open="open"
      :popover-class="popoverClasses"
      popover-width="auto"
      trigger="manual"
      arrow-position="top-right"
    >
      <template #reference>
        <button
          :disabled="disabled"
          class="vc-split-button__menubutton"
          @click="open = true"
        >
          <i
            :class="{'is-open': open}"
            class="vc-icon-down"
          />
        </button>
      </template>
      <div
        ref="dropdown"
        class="flex flex-col divide-y divide-field-borders"
      >
        <div
          v-for="(option, i) in options"
          :key="`option-${i}`"
          :class="`hover:bg-${color}-actions-bg--focus size-${size}`"
          class="vc-split-button__dropdown-option"
          @click="setOption(option)"
        >
          <i
            v-if="option.icon"
            :class="option.icon"
            class="option-icon"
          />
          {{ option.label }}
        </div>
      </div>
    </VcPopover>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue'
import VcPopover from '@/components/VcPopover/VcPopover.vue'
import { VcSplitButtonColor, VcSplitButtonOption, VcSplitButtonOptions, VcSplitButtonSize } from './VcSplitButton.types'

const CLASS_FOR_COLOR = 'vc-split-button--'
const DATA_TEST_NAME_DEFAULT = `split-button-${Date.now()}`
const DEFAULT_COLOR = 'primary'
const DEFAULT_SIZE = 'default'

export default defineComponent({
  name: 'VcSplitButton',
  components: { VcPopover },
  props: {
    color: {
      type: String as PropType<VcSplitButtonColor>,
      default: DEFAULT_COLOR
    },
    options: {
      type: Array as PropType<VcSplitButtonOptions>,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    },
    dataTestName: {
      type: String,
      default: DATA_TEST_NAME_DEFAULT
    },
    size: {
      type: String as PropType<VcSplitButtonSize>,
      default: DEFAULT_SIZE
    }
  },
  emits: ['click', 'change'],
  data: () => ({
    open: false,
    selectedValue: null as VcSplitButtonOption
  }),
  computed: {
    containerClasses () {
      const colorClass = CLASS_FOR_COLOR + this.color
      return [
        colorClass,
        {
          'vc-split-button--disabled': this.disabled
        },
        this.size === DEFAULT_SIZE || `vc-split-button--${this.size}`
      ]
    },
    popoverClasses () {
      const classMain = 'vc-split-button__dropdown'

      return [
        classMain,
        this.size === 'large' && 'offset-y-1',
        `is--${this.size}`
      ].join(' ')
    }
  },
  mounted () {
    this.selectedValue = this.options[0] || null
  },
  methods: {
    closeDropdown (): void {
      this.open = false
    },
    setOption (option: VcSplitButtonOption): void {
      this.selectedValue = option
      this.closeDropdown()
      this.$emit('change', option)
    },
    handleClick (): void {
      this.$emit('click', this.selectedValue)
    }
  }
})
</script>

<style lang="scss">
@use 'sass:color';
 @mixin colorScheme($color) {
   @apply border-#{$color}-actions transition-all duration-300;
   .vc-split-button__button {
     .content-icon {
       @apply text-#{$color}-actions;
     }
   }
   .vc-split-button__menubutton {
     @apply text-#{$color}-actions border-#{$color}-actions;
   }
   &:hover:not(.vc-split-button--disabled) {
     @apply bg-#{$color}-actions-bg--focus;
     .vc-split-button__button, .vc-split-button__menubutton {
       @apply active:bg-#{$color}-actions-bg--pressed;
     }
   }
 }

  .vc-split-button {
    @apply
    inline-flex
    items-stretch
    relative
    items-center
    justify-between
    cursor-pointer
    bg-transparent
    outline-none
    rounded-sm
    border
    border-inactive-elements
    leading-none
    max-w-full
    ;
    min-width: 200px;
    &__dropdown-option {
      @apply flex items-center text-sm py-2 px-3 whitespace-nowrap cursor-pointer relative z-1 transition-all duration-300;
      &.size-large {
        @apply py-3 text-base;
      }
      .option-icon {
        @apply mr-2;
      }
    }
    &__button {
      @apply py-2 px-3 flex items-center text-base flex-grow truncate overflow-hidden rounded-l-sm;
      max-width: calc(100% - 2rem);
      .content-icon {
        @apply text-base mr-2 flex-shrink-0;
      }
    }
    &__menubutton {
      @apply flex justify-center flex-shrink-0 items-center border-l border-inactive-elements py-2 w-8 h-full rounded-r-sm;
      i {
        @apply transition-all duration-100 text-base;
        &.is-open {
          transform: rotate(180deg);
        }
      }
    }
    /* Size */
    &--large {
      @apply border-2;
      .vc-split-button__button {
        @apply py-2.5 text-base font-semibold;
        max-width: calc(100% - 2.25rem);
        .content-icon {
          @apply text-lg;
        }
      }
      .vc-split-button__menubutton {
        @apply py-2.5 text-base font-semibold w-9 border-l-2;
        i {
          @apply text-lg;
        }
      }
    }
    &--small {
      @apply border;
      .vc-split-button__button {
        @apply py-1 text-sm font-normal;
        max-width: calc(100% - 1.75rem);
        .content-icon {
          @apply text-base h-4;
        }
      }
      .vc-split-button__menubutton {
        @apply py-1 text-sm font-normal w-7 border-l;
        i {
          @apply text-base;
        }
      }
    }

    /* Colors: */
    &--primary {
      @include colorScheme(primary)
    }
    &--secondary {
      @include colorScheme(secondary)
    }
    &--destructive {
      @include colorScheme(destructive)
    }
    &--success {
      @include colorScheme(success)
    }
    &--warning {
      @include colorScheme(warning)
    }
    &--disabled {
      @apply opacity-50 cursor-not-allowed;
      .vc-split-button__button {
        @apply cursor-not-allowed;
      }
      .vc-split-button__menubutton {
        @apply cursor-not-allowed;
      }
    }
  }
.vc-split-button__dropdown {
  @apply w-full max-w-full;
  &.vc-popover--top-right {
    transform: translateY(1px);
    &.offset-y-1 {
      transform: translateY(2px);
    }
  }
  &.vc-popover--bottom-right {
    transform: translateY(-1px);
    &.offset-y-1 {
      transform: translateY(-2px);
    }
  }
}

[dir='rtl'] {
  $largeOffset: calc(100% - 2.25rem);
  $defaultOffset: calc(100% - 2rem);
  $smallOffset: calc(100% - 1.75rem);
  .is--large {
    --drop-btn-offset: #{$largeOffset}
  }
  .is--default {
    --drop-btn-offset: #{$defaultOffset}
  }
  .is--small {
    --drop-btn-offset: #{$smallOffset}
  }
  .vc-split-button {
    &__button {
      @apply rounded-l-none rounded-r-sm;
      .content-icon {
        @apply mr-0 ml-2;
      }
    }
    &__menubutton {
      @apply border-l-0 border-r rounded-r-none rounded-l-sm;
    }
    &__dropdown-option {
      .option-icon {
        @apply mr-0 ml-2;
      }
    }
    &--large {
      .vc-split-button__menubutton {
        @apply border-r-2;
      }
    }
  }
  .vc-split-button__dropdown {
    &.vc-popover--top-right {
      transform: translate(var(--drop-btn-offset, 2rem), 1px);
      &.offset-y-1 {
        transform: translate(var(--drop-btn-offset, 2rem), 2px);
      }
    }
    &.vc-popover--bottom-right {
      transform: translate(var(--drop-btn-offset, 2rem), -2px);
      &.offset-y-1 {
        transform: translate(var(--drop-btn-offset, 2rem), -3px);
      }
    }
  }
}
</style>
