<template>
	<el-dialog
		v-model="dialogVisible"
		:title="t('shared.createWorkflow.title')"
		width="600px"
		:close-on-click-modal="false"
		@close="handleClose"
	>
		<el-form ref="formRef" :model="form" :rules="rules" label-width="90px" class="create-form">
			<el-form-item :label="t('shared.createWorkflow.fields.name')" prop="name">
				<el-input
					v-model="form.name"
					:placeholder="t('shared.createWorkflow.placeholders.name')"
					maxlength="50"
					show-word-limit
				/>
			</el-form-item>

			<el-form-item :label="t('shared.createWorkflow.fields.remark')" prop="remark">
				<el-input
					v-model="form.remark"
					type="textarea"
					:placeholder="t('shared.createWorkflow.placeholders.remark')"
					:rows="2"
					maxlength="200"
					show-word-limit
				/>
			</el-form-item>

			<el-form-item :label="t('shared.createWorkflow.fields.cover')" prop="profilePhoto">
				<div class="w-full">
					<FileUpload v-model="coverFile" :fileTypes="['image']" :allowLinkInput="false" />
				</div>
			</el-form-item>
		</el-form>

		<template #footer>
			<div class="dialog-footer mt-2">
				<el-button @click="handleCancel">{{ t('common.cancel') }}</el-button>
				<el-button type="primary" :loading="loading" @click="handleSubmit">
					{{ t('common.confirm') }}
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { agent } from '@repo/api-service'
import { useI18n } from '@/composables/useI18n'

import FileUpload from '../fileUpload/FileUploadInput.vue'
import type { WorkflowUploadFile } from '../fileUpload/shared'

interface ViewPort {
	x: number
	y: number
	zoom: number
}

interface CreateWorkflowForm {
	name: string
	remark: string
	profilePhoto: string
	viewPort: ViewPort
}

const props = defineProps({
	visible: {
		type: Boolean,
		default: false
	}
})

const emit = defineEmits<{
	close: []
	success: [id: string]
}>()

const { t } = useI18n()
const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()
const coverFile = ref<WorkflowUploadFile>()

const createDefaultForm = (): CreateWorkflowForm => ({
	name: '',
	remark: '',
	profilePhoto: '',
	viewPort: {
		x: 0,
		y: 0,
		zoom: 1
	}
})

const form = ref<CreateWorkflowForm>(createDefaultForm())

const rules: FormRules<CreateWorkflowForm> = {
	name: [
		{
			required: true,
			message: t('shared.createWorkflow.validation.nameRequired'),
			trigger: 'blur'
		}
	]
}

watch(
	() => props.visible,
	(val) => {
		dialogVisible.value = val
		if (val) {
			// 打开时重置校验
			formRef.value?.clearValidate()
		}
	},
	{ immediate: true }
)

const resetForm = () => {
	form.value = createDefaultForm()
	formRef.value?.clearValidate()
}

const handleClose = () => {
	resetForm()
	emit('close')
}

const handleCancel = () => {
	dialogVisible.value = false
	handleClose()
}

const handleSubmit = async () => {
	if (!formRef.value) return

	try {
		loading.value = true
		await formRef.value.validate()

		const payload = {
			name: form.value.name,
			remark: form.value.remark || '',
			profilePhoto: coverFile.value?.id || '',
			viewPort: form.value.viewPort
		}

		const response = await agent.postAgentDoEditAgent({
			data: payload
		})

		if (response?.isSuccess) {
			const id = (response as any).result as string
			ElMessage.success(t('shared.createWorkflow.success'))
			dialogVisible.value = false
			resetForm()
			if (id) {
				emit('success', id)
			} else {
				emit('close')
			}
		} else {
			ElMessage.error(t('shared.createWorkflow.error'))
		}
	} catch (error) {
		console.error('create workflow error', error)
		ElMessage.error(t('shared.createWorkflow.error'))
	} finally {
		loading.value = false
	}
}

defineExpose({
	open: () => {
		dialogVisible.value = true
	},
	close: handleClose
})
</script>

<style scoped lang="less">
.create-form {
	padding-top: 8px;
}

.viewport-inputs {
	display: flex;
	align-items: center;
	gap: 8px;
}

.viewport-inputs .sep {
	color: var(--text-secondary);
	font-size: 12px;
}

.tag-tip {
	color: var(--text-secondary);
	font-size: 12px;
}

.dialog-footer {
	display: flex;
	justify-content: flex-end;
	gap: 8px;
}
</style>
