<script lang="ts" setup>
import { computed } from 'vue'
import { Handle, type Position, type ValidConnectionFunc } from '@vue-flow/core'
import HandlePort from './HandlePort.vue'

const props = defineProps<{
	nodeId?: string
	handleId: string
	handleClasses?: string | string[]
	position: Position
	offset?: Record<string, string>
	isValidConnection?: ValidConnectionFunc
	type: 'source' | 'target'
	label?: string
	maxConnections?: number
	connectionsCount: number
	labelStyle?: Record<string, any>
}>()

const emit = defineEmits<{
	add: [payload: { handleId: string; event: MouseEvent }]
}>()

const connectionsLimitReached = computed(() => {
	return props.maxConnections && props.connectionsCount >= props.maxConnections
})

const isConnectableStart = computed(() => {
	if (connectionsLimitReached.value) return false

	return props.type === 'source'
})

const isConnectableEnd = computed(() => {
	if (connectionsLimitReached.value) return false

	return props.type === 'target'
})
</script>

<template>
	<Handle
		v-bind="$attrs"
		:id="handleId"
		:class="$style.handle"
		:type="type"
		:position="position"
		:style="offset"
		:connectable-start="isConnectableStart"
		:connectable-end="isConnectableEnd"
		:is-valid-connection="isValidConnection"
	>
		<HandlePort
			:node-id="nodeId"
			:position="position"
			:type="type"
			:label="label"
			:label-style="labelStyle"
			:id="handleId"
			:show-add-action="type === 'source' && connectionsCount === 0"
			@add="emit('add', { handleId, event: $event })"
		/>
	</Handle>
</template>

<style lang="less" module>
:global(.vue-flow__handle).handle {
	/* stylelint-disable-next-line @n8n/css-var-naming */
	--handle--indicator--width: 16px;
	/* stylelint-disable-next-line @n8n/css-var-naming */
	--handle--indicator--height: 16px;

	width: 16px;
	height: 16px;
	display: inline-flex;
	justify-content: center;
	align-items: center;
	border: 0;
	z-index: 20;
	background: transparent;
	border-radius: 0;
	overflow: visible;

	&.inputs.main {
		cursor: default;
	}
}

.renderType {
	&.top {
		margin-bottom: -16px;
		transform: translate(0%, -50%);
	}

	&.right {
		margin-left: -16px;
		transform: translate(50%, 0%);
	}

	&.left {
		margin-right: -16px;
		transform: translate(-50%, 0%);
	}

	&.bottom {
		margin-top: -16px;
		transform: translate(0%, 50%);
	}
}
</style>
