<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" class="list-spin">
        <div class="list-body" :class="{ 'list-body--empty': workflows.length === 0 }">
          <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 />
      <div class="canvas-area">
        <FlowCanvas
          :nodes="flowNodes"
          :edges="flowEdges"
          :saving="isLoading"
          :executing="isExecuting"
          @save="handleSave"
          @execute="handleExecute"
          @clear="handleClear"
          @node-select="handleNodeSelect"
          @node-drop="handleNodeDrop"
          @update:edges="flowEdges = $event"
        />
        <!-- Execution history panel -->
        <div class="execution-history">
          <div class="history-header" @click="showHistory = !showHistory">
            <span>执行历史 ({{ executionHistoryTotal }})</span>
            <UpOutlined v-if="showHistory" />
            <DownOutlined v-else />
          </div>
          <div v-if="showHistory" class="history-body">
            <a-table
              :data-source="executionHistory"
              :columns="historyColumns"
              :pagination="false"
              size="small"
              row-key="execution_id"
              :scroll="{ y: 200 }"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="getStatusColor(record.status)">{{ getStatusLabel(record.status) }}</a-tag>
                </template>
                <template v-else-if="column.key === 'started_at'">
                  {{ formatTime(record.started_at) }}
                </template>
                <template v-else-if="column.key === 'completed_at'">
                  {{ formatTime(record.completed_at) }}
                </template>
              </template>
            </a-table>
          </div>
        </div>
      </div>
      <PropertyPanel
        :node-data="selectedNodeData"
        @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,
  UpOutlined,
  DownOutlined,
} 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('{}')
const showHistory = ref(false)

// Execution history
const executionHistory = computed(() => store.executionHistory)
const executionHistoryTotal = computed(() => store.executionHistoryTotal)

const historyColumns = [
  { title: '执行ID', dataIndex: 'execution_id', key: 'execution_id', ellipsis: true, width: 120 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
  { title: '开始时间', dataIndex: 'started_at', key: 'started_at', width: 160 },
  { title: '完成时间', dataIndex: 'completed_at', key: 'completed_at', width: 160 },
]

// 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()
})

function getStatusColor(status: string): string {
  const colors: Record<string, string> = {
    pending: 'default',
    running: 'processing',
    paused: 'warning',
    completed: 'success',
    failed: 'error',
    cancelled: 'default',
  }
  return colors[status] || 'default'
}

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

function formatTime(iso: string | null | undefined): string {
  if (!iso) return '-'
  try {
    return new Date(iso).toLocaleString()
  } catch {
    return iso
  }
}

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)
  store.loadExecutionHistory()
}

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 handleNodeDrop(nodeType: string, position: { x: number; y: number }) {
  store.addNode(nodeType, position)
}

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: var(--space-4);
}

.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--space-4);
}

.list-header h3 {
  margin: 0;
  font-size: var(--font-md);
}

.list-spin {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.list-spin :deep(.ant-spin-container) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.list-body {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.list-body--empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.list-body--empty :deep(.ant-empty) {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.workflow-item {
  display: flex;
  align-items: center;
  padding: var(--space-3) var(--space-4);
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  cursor: pointer;
  transition: all var(--transition-fast);
  gap: var(--space-3);
}

.workflow-item:hover {
  border-color: var(--color-primary);
  box-shadow: var(--shadow-md);
}

.item-name {
  font-weight: var(--font-weight-medium);
  font-size: var(--font-base);
}

.item-meta {
  display: flex;
  gap: var(--space-2);
  font-size: var(--font-xs);
  color: var(--text-tertiary);
}

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

.canvas-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  overflow: hidden;
}

.execution-history {
  border-top: 1px solid var(--border-color);
  background: var(--bg-secondary);
  flex-shrink: 0;
}

.history-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-2) var(--space-4);
  cursor: pointer;
  font-size: var(--font-sm);
  font-weight: var(--font-weight-medium);
  color: var(--text-secondary);
  user-select: none;
}

.history-header:hover {
  background: var(--bg-tertiary);
}

.history-body {
  padding: 0 var(--space-4) var(--space-2);
}

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

.workflow-name {
  font-weight: var(--font-weight-semibold);
  font-size: var(--font-base);
  color: var(--text-primary);
}
</style>
