<template>
  <div class="flow-canvas" ref="canvasRef" @drop="onDrop" @dragover="onDragOver">
    <div class="canvas-toolbar">
      <a-space>
        <a-button size="small" @click="$emit('save')" :loading="saving">
          <template #icon><SaveOutlined /></template>
          保存
        </a-button>
        <a-button size="small" type="primary" @click="$emit('execute')" :loading="executing">
          <template #icon><PlayCircleOutlined /></template>
          执行
        </a-button>
        <a-button size="small" @click="onValidate">
          <template #icon><CheckCircleOutlined /></template>
          验证
        </a-button>
        <a-button size="small" danger @click="$emit('clear')">
          <template #icon><DeleteOutlined /></template>
          清空
        </a-button>
      </a-space>
    </div>
    <VueFlow
      v-model:nodes="nodes"
      v-model:edges="edges"
      :node-types="nodeTypes"
      :default-edge-options="defaultEdgeOptions"
      :snap-to-grid="true"
      :snap-grid="[15, 15]"
      fit-view-on-init
      @node-click="onNodeClick"
      @pane-click="onPaneClick"
      @connect="onConnect"
    >
      <Background :gap="20" :size="1" />
      <Controls />
      <MiniMap />
    </VueFlow>
  </div>
</template>

<script setup lang="ts">
import { ref, markRaw } from 'vue'
import { VueFlow } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
import { Controls } from '@vue-flow/controls'
import { MiniMap } from '@vue-flow/core'
import {
  SaveOutlined,
  PlayCircleOutlined,
  CheckCircleOutlined,
  DeleteOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import SkillNode from './SkillNode.vue'
import ConditionNode from './ConditionNode.vue'
import ApprovalNode from './ApprovalNode.vue'
import type { WorkflowNodeData } from '@/utils/workflowSerializer'

const props = defineProps<{
  nodes: any[]
  edges: any[]
  saving?: boolean
  executing?: boolean
}>()

const emit = defineEmits<{
  save: []
  execute: []
  clear: []
  'update:nodes': [nodes: any[]]
  'update:edges': [edges: any[]]
  'node-select': [nodeId: string | null]
}>()

const canvasRef = ref<HTMLElement>()

const nodeTypes = {
  skill: markRaw(SkillNode),
  condition: markRaw(ConditionNode),
  approval: markRaw(ApprovalNode),
}

const defaultEdgeOptions = {
  animated: true,
  style: { stroke: '#1890ff', strokeWidth: 2 },
}

function onDragOver(event: DragEvent) {
  event.preventDefault()
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move'
  }
}

function onDrop(event: DragEvent) {
  const nodeType = event.dataTransfer?.getData('application/vueflow')
  if (!nodeType) return

  const { left, top } = (canvasRef.value?.getBoundingClientRect() || { left: 0, top: 0 })
  const position = {
    x: event.clientX - left - 100,
    y: event.clientY - top - 50,
  }

  emit('node-select', 'drop')
  // The parent will handle adding the node via the store
  // We emit a custom event that the parent can listen to
  // For now, we'll use a direct approach
}

function onNodeClick({ node }: { node: any }) {
  emit('node-select', node.id)
}

function onPaneClick() {
  emit('node-select', null)
}

function onConnect(params: any) {
  // Add new edge
  const newEdge = {
    id: `edge-${params.source}-${params.target}`,
    source: params.source,
    target: params.target,
    sourceHandle: params.sourceHandle,
    targetHandle: params.targetHandle,
    animated: true,
    style: { stroke: '#1890ff', strokeWidth: 2 },
  }
  emit('update:edges', [...props.edges, newEdge])
}

function onValidate() {
  // Basic validation
  if (props.nodes.length === 0) {
    message.warning('工作流为空，请添加节点')
    return
  }
  // Check for nodes without connections (except the first)
  const connectedSources = new Set(props.edges.map((e: any) => e.source))
  const connectedTargets = new Set(props.edges.map((e: any) => e.target))
  const allConnected = new Set([...connectedSources, ...connectedTargets])

  const orphanNodes = props.nodes.filter((n: any) => !allConnected.has(n.id))
  if (orphanNodes.length > 0 && props.nodes.length > 1) {
    message.warning(`存在未连接的节点: ${orphanNodes.map((n: any) => n.data?.label).join(', ')}`)
    return
  }

  message.success('工作流验证通过')
}
</script>

<style scoped>
.flow-canvas {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.canvas-toolbar {
  padding: 8px 12px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  z-index: 10;
}

.flow-canvas :deep(.vue-flow) {
  flex: 1;
}
</style>

<style>
/* Global styles for Vue Flow */
@import '@vue-flow/core/dist/style.css';
@import '@vue-flow/core/dist/theme-default.css';
@import '@vue-flow/controls/dist/style.css';
</style>
