<script setup lang="ts">
import { ref, computed } from 'vue'
import { StickyNote } from '@repo/ui'
import { NodeResizer } from '@vue-flow/node-resizer'
import type { OnResize } from '@vue-flow/node-resizer'

import type { XYPosition } from '@vue-flow/core'
import { useCanvasNodeContext } from '../../../../hooks/useCanvasNodeContext'

// make sure to include the necessary styles!
import '@vue-flow/node-resizer/dist/style.css'

defineOptions({
	inheritAttrs: false
})

const node = useCanvasNodeContext()

const emit = defineEmits<{
	update: [parameters: Record<string, unknown>]
	move: [position: XYPosition]
	activate: [id: string]
	deactivate: [id: string]
	'open:contextmenu': [event: MouseEvent]
}>()

const data = computed(() => node.props.value.data)
const isReadOnly = computed(() => node.props.value.readOnly ?? false)

const modelValue = computed({
	get() {
		return data.value?.content
	},
	set(value) {
		if (data.value?.content) {
			data.value.content = value
		}
	}
})

const editMode = ref(false)

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

	return classes
})

const handleSetEditMode = (edit: boolean) => {
	if (!isReadOnly.value) {
		editMode.value = edit
	}
}

/**
 * Resizing
 */

function onResize(event: OnResize) {
	emit('move', {
		x: event.params.x,
		y: event.params.y
	})

	emit('update', {
		...(event.params.width ? { width: event.params.width } : {}),
		...(event.params.height ? { height: event.params.height } : {})
	})
}
</script>

<template>
	<NodeResizer
		:min-height="80"
		:min-width="150"
		:height="data?.height"
		:width="data?.width"
		:is-visible="!isReadOnly && node.props.value.selected"
		handleClassName="bg-transparent! border-transparent!"
		lineClassName="border-transparent!"
		@resize="onResize"
	/>

	<div class="sticky-note__node relative rounded-4px" :class="nodeClass">
		<StickyNote
			v-model="modelValue"
			:minHeight="100"
			:minWidth="120"
			:width="data?.width"
			:height="data?.height"
			:backgroundColor="data?.color"
			:readOnly="node.props.value.readOnly"
			:editMode="editMode"
			@dblclick.stop="handleSetEditMode"
			@edit="handleSetEditMode"
		/>
	</div>
</template>
