<script setup lang="ts">
import { computed } from 'vue'
import { Icon } from '@repo/ui'

import { useCanvasNodeContext } from '../../../../hooks/useCanvasNodeContext'
import { useVueFlowContext } from '../../../../hooks/useVueFlowContext'
import { getNodeExecutionStatus } from '../../../../utils/execution-status'

const node = useCanvasNodeContext()
const { nodeMap } = useVueFlowContext()

const nodeClass = computed(() => {
	let classes: string[] = []
	if (node.props.value.selected) {
		classes.push('ring-6px', 'ring-#e0e2e7')
	}

	return classes
})
const nodeData = computed(() => node.props.value.data)

const nodeType = computed(() => nodeMap.value[nodeData.value?.nodeType!])
const executionStatus = computed(() => getNodeExecutionStatus(node.props.value.node))

const resolvedIcon = computed(() => {
	const icon = `${nodeType.value?.icon || ''}`
	if (!icon) return 'lucide:cloud'
	if (icon.startsWith('data:image/')) return icon
	if (icon.length > 64 && /^[A-Za-z0-9+/=]+$/.test(icon)) {
		return `data:image/png;base64,${icon}`
	}
	return icon
})

const isImageIcon = computed(() => resolvedIcon.value.startsWith('data:image/'))
</script>

<template>
	<el-tooltip :content="nodeType?.displayName || '节点标题'">
		<div
			:data-execution-status="executionStatus"
			:data-pending="nodeData?.pending ? 'true' : 'false'"
			:class="nodeClass"
			class="canvas-node-status-shell bg-#fff rounded-8px relative border-1.5px border-solid border-transparent"
		>
			<div className="w-full h-full relative flex items-center justify-center">
				<div
					class="relative flex-shrink-0 flex items-center justify-center w-10 h-10 rounded-lg"
					:style="{ background: nodeType?.iconColor }"
				>
					<div
						class="absolute inset-0 bg-gradient-to-br from-white/30 to-transparent rounded-lg"
					></div>
					<img
						v-if="isImageIcon"
						:src="resolvedIcon"
						alt="node icon"
						class="relative z-10 w-20px h-20px object-contain"
					/>
					<Icon v-else :icon="resolvedIcon" color="#ffffff" class="relative z-10" :size="20" />
				</div>
			</div>
		</div>
	</el-tooltip>
</template>
