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

import { Icon } from '@repo/ui'

import { useCanvasNodeContext } from '../../../hooks/useCanvasNodeContext'

const emit = defineEmits<{
	delete: []
	run: []
}>()

const props = defineProps<{
	hovered?: boolean
}>()

const node = useCanvasNodeContext()

const barState = ref(false)

const BarHandleClick = (state: string) => {
	barState.value = false
	if (state === 'node-run') {
		emit('run')
	} else if (state === 'node-edit') {
	}
}

const onDelete = () => {
	emit('delete')
}

const delayedHovered = ref()
const delayedHoveredSetTimeoutRef = ref<ReturnType<typeof setTimeout> | null>(null)
const delayedHoveredTimeout = 600

watch(
	() => props?.hovered,
	(isHovered) => {
		if (isHovered) {
			if (delayedHoveredSetTimeoutRef.value) clearTimeout(delayedHoveredSetTimeoutRef.value)
			delayedHovered.value = true
		} else {
			delayedHoveredSetTimeoutRef.value = setTimeout(() => {
				delayedHovered.value = false
			}, delayedHoveredTimeout)
		}
	},
	{ immediate: true }
)

const renderToolbar = computed(
	() => (delayedHovered.value && !node.props.value.readOnly) || barState.value
)
</script>

<template>
	<div class="node-tools absolute top--32px right-0" v-if="renderToolbar">
		<div class="bar flex items-center">
			<Icon
				icon="lucide:play"
				width="12"
				height="12"
				class="text-gray-400 p-2 hover:cursor-pointer hover:bg-gray-200"
				@click="BarHandleClick('node-run')"
			/>
			<el-popover v-model:visible="barState" trigger="click" width="240px">
				<template #reference>
					<Icon
						icon="lucide:ellipsis"
						width="12"
						height="12"
						class="text-gray-400 p-2 hover:cursor-pointer hover:bg-gray-200"
					/>
				</template>
				<div class="modal flex flex-col">
					<ul class="text-sm">
						<li @click.stop="BarHandleClick('node-run')">
							<p>运行此步骤</p>
						</li>
						<li @click.stop="BarHandleClick('node-edit')">
							<p>更改节点</p>
						</li>
						<li @click.stop="BarHandleClick('node-copy')">
							<p>拷贝</p>
						</li>
						<li @click.stop="onDelete">
							<p>删除</p>
						</li>
						<li @click.stop="BarHandleClick('node-doc')">
							<p>查看文档</p>
						</li>
					</ul>
				</div>
			</el-popover>
		</div>
	</div>
</template>

<style scoped lang="less">
.modal {
	ul {
		margin: 0;
		padding: 0;
	}
	li {
		padding: 6px;
		text-align: left;
		list-style: none;
		border-bottom: 1px solid #eee;
		margin: 0;
		box-sizing: border-box;
		p {
			margin: 0;
			padding: 10px 20px;
			border-radius: 12px;
			&:hover {
				cursor: pointer;
				background: #e5eff6;
			}
		}
	}
}
</style>
