<template>
  <div class="workflow-editor">
    <!-- Workflow list sidebar -->
    <div v-if="!currentWorkflow" class="workflow-list">
      <div class="list-header">
        <h3>工作流列表</h3>
        <a-button type="primary" size="small" @click="handleCreate">
          <template #icon><PlusOutlined /></template>
          新建
        </a-button>
      </div>
      <a-spin :spinning="isLoading">
        <div class="list-body">
          <div
            v-for="wf in workflows"
            :key="wf.workflow_id"
            class="workflow-item"
            @click="handleSelectWorkflow(wf.workflow_id)"
          >
            <div class="item-name">{{ wf.name }}</div>
            <div class="item-meta">
              <span>{{ wf.stage_count }} 个阶段</span>
              <span>v{{ wf.version }}</span>
            </div>
            <a-button
              size="small"
              type="text"
              danger
              @click.stop="handleDelete(wf.workflow_id)"
            >
              <template #icon><DeleteOutlined /></template>
            </a-button>
          </div>
          <a-empty v-if="workflows.length === 0" description="暂无工作流" />
        </div>
      </a-spin>
    </div>

    <!-- Workflow editor canvas -->
    <div v-else class="editor-main">
      <NodePalette />
      <FlowCanvas
        :nodes="flowNodes"
        :edges="flowEdges"
        :saving="isLoading"
        :executing="isExecuting"
        @save="handleSave"
        @execute="handleExecute"
        @clear="handleClear"
        @node-select="handleNodeSelect"
        @update:edges="flowEdges = $event"
      />
      <PropertyPanel
        :node-data="selectedNodeData"
        @update-field="handleUpdateField"
        @update-config="handleUpdateConfig"
        @delete-node="handleDeleteNode"
      />
    </div>

    <!-- Back button when editing -->
    <div v-if="currentWorkflow" class="back-bar">
      <a-button size="small" @click="handleBack">
        <template #icon><ArrowLeftOutlined /></template>
        返回列表
      </a-button>
      <span class="workflow-name">{{ currentWorkflow.name }}</span>
      <a-tag v-if="currentExecution" :color="executionStatusColor">
        {{ executionStatusLabel }}
      </a-tag>
    </div>

    <!-- Execution dialog -->
    <a-modal
      v-model:open="showExecuteDialog"
      title="执行工作流"
      @ok="confirmExecute"
      ok-text="执行"
      cancel-text="取消"
    >
      <a-form layout="vertical">
        <a-form-item label="输入变量 (JSON)">
          <a-textarea
            v-model:value="executeVariables"
            placeholder='{"key": "value"}'
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  DeleteOutlined,
  ArrowLeftOutlined,
} from '@ant-design/icons-vue'
import { useWorkflowStore } from '@/stores/workflow'
import NodePalette from '@/components/workflow/NodePalette.vue'
import FlowCanvas from '@/components/workflow/FlowCanvas.vue'
import PropertyPanel from '@/components/workflow/PropertyPanel.vue'

const store = useWorkflowStore()

const showExecuteDialog = ref(false)
const executeVariables = ref('{}')

// Computed from store
const workflows = computed(() => store.workflows)
const currentWorkflow = computed(() => store.currentWorkflow)
const currentExecution = computed(() => store.currentExecution)
const isExecuting = computed(() => store.isExecuting)
const isLoading = computed(() => store.isLoading)
const flowNodes = computed({
  get: () => store.flowNodes,
  set: (val) => { store.flowNodes = val },
})
const flowEdges = computed({
  get: () => store.flowEdges,
  set: (val) => { store.flowEdges = val },
})
const selectedNodeData = computed(() => store.selectedNodeData)

const executionStatusColor = computed(() => {
  const colors: Record<string, string> = {
    pending: 'default',
    running: 'processing',
    paused: 'warning',
    completed: 'success',
    failed: 'error',
    cancelled: 'default',
  }
  return colors[currentExecution.value?.status || 'pending'] || 'default'
})

const executionStatusLabel = computed(() => {
  const labels: Record<string, string> = {
    pending: '等待中',
    running: '运行中',
    paused: '已暂停',
    completed: '已完成',
    failed: '已失败',
    cancelled: '已取消',
  }
  return labels[currentExecution.value?.status || 'pending'] || '未知'
})

onMounted(() => {
  store.loadWorkflows()
})

async function handleCreate() {
  const name = `工作流 ${workflows.value.length + 1}`
  const wf = await store.createWorkflow(name)
  if (wf) {
    message.success('工作流已创建')
  }
}

async function handleSelectWorkflow(workflowId: string) {
  await store.loadWorkflow(workflowId)
}

async function handleDelete(workflowId: string) {
  const success = await store.deleteWorkflow(workflowId)
  if (success) {
    message.success('工作流已删除')
  }
}

async function handleSave() {
  const success = await store.saveWorkflow()
  if (success) {
    message.success('工作流已保存')
  } else {
    message.error('保存失败')
  }
}

function handleExecute() {
  showExecuteDialog.value = true
}

async function confirmExecute() {
  showExecuteDialog.value = false
  try {
    const vars = JSON.parse(executeVariables.value)
    await store.executeWorkflow(vars)
    message.success('工作流开始执行')
  } catch {
    message.error('变量格式错误，请输入有效的 JSON')
  }
}

function handleClear() {
  store.clearCanvas()
}

function handleNodeSelect(nodeId: string | null) {
  store.selectNode(nodeId)
}

function handleUpdateField(field: string, value: unknown) {
  if (store.selectedNodeId) {
    store.updateNodeData(store.selectedNodeId, { [field]: value })
  }
}

function handleUpdateConfig(key: string, value: unknown) {
  if (store.selectedNodeId && store.selectedNodeData) {
    store.updateNodeData(store.selectedNodeId, {
      config: { ...store.selectedNodeData.config, [key]: value },
    })
  }
}

function handleDeleteNode() {
  if (store.selectedNodeId) {
    store.removeNode(store.selectedNodeId)
  }
}

function handleBack() {
  store.currentWorkflow = null
  store.flowNodes = []
  store.flowEdges = []
  store.selectedNodeId = null
  store.currentExecution = null
  store.loadWorkflows()
}
</script>

<style scoped>
.workflow-editor {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.workflow-list {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 16px;
}

.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
}

.list-body {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.workflow-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  gap: 12px;
}

.workflow-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.12);
}

.item-name {
  font-weight: 500;
  font-size: 14px;
  flex: 1;
}

.item-meta {
  display: flex;
  gap: 8px;
  font-size: 12px;
  color: #999;
}

.editor-main {
  display: flex;
  flex: 1;
  height: 100%;
  overflow: hidden;
}

.back-bar {
  position: absolute;
  top: 0;
  left: 200px;
  right: 300px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.95);
  border-bottom: 1px solid #f0f0f0;
  z-index: 20;
}

.workflow-name {
  font-weight: 600;
  font-size: 14px;
  color: #333;
}
</style>
