<template>
	<el-popover
		ref="popoverRef"
		width="240px"
		trigger="click"
		:disabled="publishNodes.length <= 1 || isPublishing"
	>
		<div v-if="publishNodes.length > 1" class="publish-selector">
			<div class="publish-selector__title">{{ t('pages.editor.selectPublishNode') }}</div>
			<button
				v-for="node in publishNodes"
				:key="node.id"
				type="button"
				class="publish-selector__item"
				@click="handleSelectPublishNode(node.id)"
			>
				<span class="publish-selector__name">{{ node.name }}</span>
				<span class="publish-selector__type">{{ getNodeDisplayName(node.nodeType) }}</span>
			</button>
		</div>
		<template #reference>
			<el-button
				:type="isPublished ? 'success' : 'default'"
				size="small"
				:disabled="!publishNodes.length"
				:loading="isPublishing"
				@click="handlePublishClick"
			>
				<Icon v-if="isPublished" icon="ix:success" class="mr-1" />
				{{
					isPublished ? t('pages.editor.status.published') : t('pages.editor.status.unpublished')
				}}
			</el-button>
		</template>
	</el-popover>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage, type PopoverInstance } from 'element-plus'
import { agent } from '@repo/api-service'
import { Icon } from '@repo/ui'

import type { IWorkflow } from '@repo/workflow'

import { useI18n } from '@/composables/useI18n'
import { getNodeDisplayName } from '@/nodes/i18n'

const props = defineProps<{
	workflow: IWorkflow
}>()

const emit = defineEmits<{
	(e: 'published'): void
}>()

const { t } = useI18n()
const popoverRef = ref<PopoverInstance>()
const isPublishing = ref(false)

const PUBLISHABLE_NODE_TYPES = ['start', 'trigger-schedule', 'trigger-webhook']

const isPublished = computed(() => props.workflow?.status === 'published')

const publishNodes = computed(() => {
	return (props.workflow?.nodes || [])
		.filter((node) => {
			const nodeType = (node as any)?.nodeType || (node as any)?.data?.nodeType
			return PUBLISHABLE_NODE_TYPES.includes(nodeType || '')
		})
		.map((node) => {
			const nodeType = ((node as any)?.nodeType || (node as any)?.data?.nodeType || '') as string
			return {
				id: node.id,
				name: node.name || node.data?.title || getNodeDisplayName(nodeType) || nodeType,
				nodeType
			}
		})
})

const publishAgent = async (nodeId?: string) => {
	if (!nodeId) {
		ElMessage.warning(t('pages.editor.messages.missingPublishNode'))
		return
	}

	if (isPublishing.value) {
		return
	}

	isPublishing.value = true

	try {
		const response = await agent.postAgentDoAgentPublish({
			start_node_id: nodeId,
			appAgentId: props.workflow.id
		})

		if (response?.isSuccess) {
			props.workflow.status = 'published'
			popoverRef.value?.hide()
			ElMessage.success(t('pages.editor.messages.publishSuccess'))
			emit('published')
			return
		}

		if ((response as any)?.error) {
			ElMessage.error((response as any).error)
			return
		}

		ElMessage.error(t('pages.editor.messages.publishFailed'))
	} catch (error) {
		console.error('postAgentDoAgentPublish error', error)
		ElMessage.error(t('pages.editor.messages.publishFailed'))
	} finally {
		isPublishing.value = false
	}
}

const handlePublishClick = () => {
	if (publishNodes.value.length <= 1) {
		publishAgent(publishNodes.value[0]?.id)
	}
}

const handleSelectPublishNode = (id: string) => {
	publishAgent(id)
}
</script>

<style scoped>
.publish-selector {
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.publish-selector__title {
	font-size: 13px;
	font-weight: 600;
	color: #344054;
}

.publish-selector__item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 12px;
	width: 100%;
	padding: 10px 12px;
	border: 1px solid #e4e7ec;
	border-radius: 10px;
	background: #fff;
	cursor: pointer;
	text-align: left;
}

.publish-selector__item:hover {
	border-color: #2563eb;
	background: #f8fbff;
}

.publish-selector__name {
	font-size: 13px;
	font-weight: 600;
	color: #344054;
}

.publish-selector__type {
	font-size: 12px;
	color: #667085;
}
</style>
