<script lang="tsx">
import {
  defineComponent, nextTick, ref,
  type PropType,
  type Ref,
} from 'vue'
import useClickOutside from '../../composables/use-click-outside'
import type { DefaultTableContextActionInterface } from './DefaultTableInterfaces'

export default defineComponent({
  props: {
    onClose: {
      type: Function as PropType<() => void>,
      required: true,
    },
  },

  setup(props, { expose }) {
    const actionsDef: Ref<DefaultTableContextActionInterface[]> = ref([])
    let callbackDef: ((action: DefaultTableContextActionInterface) => void) | undefined

    const element: Ref<HTMLElement|null> = ref(null)

    async function open(actions: DefaultTableContextActionInterface[], callback: (action: DefaultTableContextActionInterface) => void): Promise<HTMLElement|undefined> {
      actionsDef.value = actions
      callbackDef = callback
      await nextTick()
      return element.value || undefined
    }

    function close() {
      actionsDef.value = []
      callbackDef = undefined
      props.onClose()
    }

    expose({
      open,
      close,
    })

    useClickOutside(element, close)

    return () => (actionsDef.value.length ? (
      <div
        ref={element}
        class="ark-ui-table-context-menu"
      >
        { actionsDef.value.map((action, i) => (
          <span
            key={i}
            onClick={() => {
              if (callbackDef) callbackDef(action)
              close()
            }}
          >
            { action.name }
          </span>
        )) }
      </div>
    ) : '')
  },
})
</script>

<style lang="scss" scoped>
.ark-ui-table-context-menu {
  position: fixed;
  left: -100vw;
  top: -100vh;

  width: fit-content;
  min-width: 164px;
  height: auto;

  display: flex;
  flex-direction: column;
  justify-content: stretch;
  align-items: stretch;

  border-radius: 4px;
  box-shadow: 0 8px 16px rgba(75, 77, 89, 0.08);
  background: #FFFFFF;
  overflow: hidden;

  transition: transform 0.1s;
  animation: onShow 0.3s;

  span {
    color: #585B69;
    font-size: 14px;
    font-weight: 400;
    padding: 12px 16px;
    line-height: 16px;
    cursor: pointer;
    user-select: none;
    pointer-events: all;

    transition: all 0.1s;

    &:hover {
      background-color: #F6F6FA;
    }

    &:active {
      opacity: 1 !important;
      background-color: #F6F6FA;
    }
  }

  &:has(> span:active) {
    transform: scale(105%);

    span {
      opacity: 0;
    }
  }
}

@keyframes onShow {
  0% {
    opacity: .5;
    transform: scaleY(0%) translateY(-50%);
  }
  100% {
    opacity: 1;
  }
}
</style>
