<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="store.flowNodes"
      v-model:edges="store.flowEdges"
      :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 />
    </VueFlow>
  </div>
</template>

<script setup lang="ts">
import { ref, markRaw, onMounted, onUnmounted } from 'vue'
import { VueFlow } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
import { Controls } from '@vue-flow/controls'
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 ParallelNode from './ParallelNode.vue'
import { useWorkflowStore } from '@/stores/workflow'

const store = useWorkflowStore()

defineProps<{
  saving?: boolean
  executing?: boolean
}>()

const emit = defineEmits<{
  save: []
  execute: []
  clear: []
  'node-select': [nodeId: string | null]
  'node-drop': [nodeType: string, position: { x: number; y: number }]
}>()

const canvasRef = ref<HTMLElement>()

const nodeTypes: Record<string, any> = {
  skill: markRaw(SkillNode),
  condition: markRaw(ConditionNode),
  approval: markRaw(ApprovalNode),
  parallel: markRaw(ParallelNode),
}

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 })
  let x = event.clientX - left - 100
  let y = event.clientY - top - 50

  // Snap to 15px grid
  x = Math.round(x / 15) * 15
  y = Math.round(y / 15) * 15

  emit('node-drop', nodeType, { x, y })
}

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

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

function onConnect(params: any) {
  // Add new edge via store (with undo support)
  const newEdge = {
    id: `edge-${params.source}-${params.target}`,
    source: params.source,
    target: params.target,
    sourceHandle: params.sourceHandle,
    targetHandle: params.targetHandle,
    animated: true,
    style: { stroke: '#7c3aed', strokeWidth: 2 },
  }
  store.addEdge(newEdge)
}

function onKeyDown(event: KeyboardEvent) {
  // Don't intercept when user is typing in an input field
  const target = event.target as HTMLElement
  if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
    return
  }

  const isUndo = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z' && !event.shiftKey
  const isRedo = ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z' && event.shiftKey)
    || ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'y')

  if (isUndo) {
    event.preventDefault()
    store.undo()
  } else if (isRedo) {
    event.preventDefault()
    store.redo()
  }
}

onMounted(() => {
  window.addEventListener('keydown', onKeyDown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', onKeyDown)
  store.disconnectExecutionWebSocket()
})

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

  const orphanNodes = store.flowNodes.filter((n: any) => !allConnected.has(n.id))
  if (orphanNodes.length > 0 && store.flowNodes.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: var(--bg-primary);
  border-bottom: 1px solid var(--border-color-split);
  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';

/* Global node execution status transitions */
.vue-flow .vue-flow__node {
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}
</style>
