<template>
  <div class="node-wrapper">
    <!-- 左侧连接点（输入） -->
    <Handle type="target" :position="Position.Left" id="left" />
    <!-- 右侧连接点（输出） -->
    <Handle type="source" :position="Position.Right" id="right" />
    <!-- 底部连接点（用于分支） -->
    <Handle type="source" :position="Position.Bottom" id="bottom" />

    <!-- 删除按钮 - 仅在可删除的分支节点上显示，在左侧 -->
    <div v-if="isDeletable" class="node-delete-btn left" @click.stop="handleDeleteBranch">
      <SvgIcon icon-class="close" size="14px" color="#d8d8d8" />
    </div>

    <!-- 删除单个节点按钮 - 在右上角，非根节点显示 -->
    <div v-if="!isRoot" class="node-delete-btn right" @click.stop="handleDeleteNode">
      <SvgIcon icon-class="close" size="14px" color="#d8d8d8" />
    </div>

    <!-- 根节点内容 -->
    <el-card v-if="isRoot" class="node-card root-style" :shadow="true">
      <div class="goal-content">
        <div class="goal-label">初始目标</div>
        <div class="goal-text">{{ goal }}</div>
      </div>
    </el-card>

    <!-- 任务节点内容 -->
    <el-card
      v-else
      class="node-card task-style"
      :class="{ 'is-branch-selected': isBranchSelected }"
      :shadow="true"
    >
      <div class="task-name">{{ task.StepName }}</div>
      <div class="agents-container">
        <el-tooltip
          v-for="agentSelection in task.AgentSelection"
          :key="agentSelection"
          effect="light"
          placement="top"
          :show-after="500"
          popper-class="task-syllabus-tooltip-popper"
        >
          <template #content>
            <div class="agent-tooltip">
              <div class="text-[16px] font-bold">{{ agentSelection }}</div>
              <div class="h-[1px] w-full bg-[#494B51] my-[4px]"></div>
              <div class="text-[12px]">
                {{ task.TaskProcess.find(i => i.AgentName === agentSelection)?.Description }}
              </div>
            </div>
          </template>
          <div class="agent-icon" :style="{ background: getAgentIcon(agentSelection).color }">
            <svg-icon :icon-class="getAgentIcon(agentSelection).icon" color="#fff" size="20px" />
          </div>
        </el-tooltip>
      </div>
    </el-card>

    <!-- 底部添加按钮 -->
    <div v-if="!isAddingBranch" class="external-add-btn" @click="startAddBranch">
      <el-icon :size="40" color="#000000">
        <CirclePlus />
      </el-icon>
    </div>

    <!-- 取消按钮（输入框显示时） -->
    <div v-else class="external-add-btn cancel-btn" @click="cancelAddBranch">
      <el-icon :size="40" color="#f56c6c">
        <Remove />
      </el-icon>
    </div>

    <!-- 外部输入框 -->
    <BranchInput
      v-if="isAddingBranch"
      ref="branchInputRef"
      @submit="handleBranchSubmit"
      @cancel="handleBranchCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { CirclePlus, Remove } from '@element-plus/icons-vue'
import { Handle, Position } from '@vue-flow/core'
import { type IRawStepTask } from '@/stores'
import { getAgentMapIcon } from '@/layout/components/config'
import BranchInput from '@/components/BranchInput/index.vue'
import SvgIcon from '@/components/SvgIcon/index.vue'

interface RootNodeData {
  goal: string
  initialInput?: string[] | string
  isRoot?: boolean
}

interface TaskNodeData {
  task: IRawStepTask
  isEditing?: boolean
  editingContent?: string
  updateKey?: number
}

const props = defineProps<{
  id: string
  data: RootNodeData | TaskNodeData
  isAddingBranch?: boolean
  isBranchSelected?: boolean
  isDeletable?: boolean
  branchId?: string
  [key: string]: any
}>()

const emit = defineEmits<{
  (e: 'add-branch', nodeId: string, branchContent: string): void
  (e: 'start-add-branch', nodeId: string): void
  (e: 'cancel-add-branch'): void
  (e: 'delete-branch', branchId: string): void
  (e: 'delete-node', nodeId: string): void
}>()

// 判断是否为根节点
const isRoot = computed(() => {
  const data = props.data as RootNodeData
  return !!data.goal || data.isRoot
})

// 根节点数据
const goal = computed(() => {
  const data = props.data as RootNodeData
  return data.goal || ''
})

const initialInput = computed(() => {
  const data = props.data as RootNodeData
  return data.initialInput
})

const displayInput = computed(() => {
  if (!initialInput.value) return false
  if (Array.isArray(initialInput.value)) {
    return initialInput.value.length > 0
  }
  return initialInput.value.trim().length > 0
})

// 任务节点数据
const task = computed(() => {
  const data = props.data as TaskNodeData
  return data.task
})

const getAgentIcon = (agentName: string) => {
  return getAgentMapIcon(agentName)
}

// 分支输入框组件引用
const branchInputRef = ref<InstanceType<typeof BranchInput>>()

// 计算属性，使用父组件传入的状态
const isAddingBranch = computed(() => props.isAddingBranch || false)

// 分支添加相关方法
const startAddBranch = () => {
  emit('start-add-branch', props.id)
  nextTick(() => {
    branchInputRef.value?.focus()
  })
}

const cancelAddBranch = () => {
  emit('cancel-add-branch')
}

const handleBranchSubmit = (value: string) => {
  emit('add-branch', props.id, value)
}

const handleBranchCancel = () => {
  emit('cancel-add-branch')
}

// 删除分支
const handleDeleteBranch = () => {
  if (props.branchId) {
    emit('delete-branch', props.branchId)
  }
}

// 删除单个节点
const handleDeleteNode = () => {
  emit('delete-node', props.id)
}

// 判断是否显示删除按钮
const isDeletable = computed(() => props.isDeletable || false)
</script>

<style scoped lang="scss">
.node-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.node-card {
  box-sizing: border-box;

  &.root-style {
    width: 200px;
    min-height: 100px;
    background: linear-gradient(var(--color-card-bg-task), var(--color-card-bg-task)) padding-box,
      linear-gradient(to right, var(--color-accent), var(--color-accent-secondary)) border-box;
    border: 2px solid transparent;

    &:hover {
      background: linear-gradient(var(--color-card-bg-task), var(--color-card-bg-task)) padding-box,
        linear-gradient(to right, var(--color-accent), var(--color-accent-secondary)) border-box;
      border: 2px solid transparent;
    }

    :deep(.el-card__body) {
      padding: 16px;
      display: flex;
      flex-direction: column;
      gap: 12px;
      position: relative;
    }
  }

  &.task-style {
    width: 150px;
    min-height: 100px;
    background-color: var(--color-card-bg-task);
    border: 2px solid var(--color-node-border);
    transition: all 0.2s ease;
    cursor: pointer;

    &:hover {
      background-color: var(--color-card-bg-task-hover);
      border-color: var(--color-node-border);
      box-shadow: var(--color-card-shadow-hover);
    }

    // 分支选中高亮样式（渐变边框）
    &.is-branch-selected {
      background: linear-gradient(var(--color-card-bg-task), var(--color-card-bg-task)) padding-box,
        linear-gradient(to right, var(--color-accent), var(--color-accent-secondary)) border-box;
      border: 2px solid transparent;
      box-sizing: border-box;

      &:hover {
        background: linear-gradient(
              var(--color-card-bg-task-hover),
              var(--color-card-bg-task-hover)
            )
            padding-box,
          linear-gradient(to right, var(--color-accent), var(--color-accent-secondary)) border-box;
        box-shadow: var(--color-card-shadow-hover);
      }
    }

    :deep(.el-card__body) {
      padding: 12px;
      display: flex;
      flex-direction: column;
      gap: 8px;
      position: relative;
    }
  }
}

// 根节点样式
.goal-content {
  text-align: center;
}

.goal-label {
  font-size: 12px;
  font-weight: bold;
  background: linear-gradient(to right, var(--color-accent), var(--color-accent-secondary));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 6px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.goal-text {
  font-size: 14px;
  font-weight: 600;
  color: var(--color-text-title-header);
  line-height: 1.6;
  word-break: break-word;
  white-space: pre-wrap;
}

// 任务节点样式
.task-name {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  color: var(--color-text-title-header);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 130px;
}

.agents-container {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  justify-content: center;
}

.agent-icon {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s ease;

  &:hover {
    transform: scale(1.1);
  }
}

.agent-tooltip {
  padding: 8px;
  max-width: 200px;
}

// 外部添加按钮
.external-add-btn {
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #fff;
  border: 2px solid #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);

  &:active {
    transform: translateX(-50%) scale(0.95);
  }

  // 取消按钮样式
  &.cancel-btn {
    border-color: #f56c6c;
    box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

// 节点删除按钮
.node-delete-btn {
  position: absolute;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #2d2d2d;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s ease;
  z-index: 100;

  // 左侧位置
  &.left {
    left: -50px;
    top: 50%;
    transform: translateY(-50%);
  }

  // 右侧位置
  &.right {
    right: -12px;
    top: -12px;
  }

  &:hover {
    background-color: #0c0c0c;
  }
}
</style>

<style>
.task-syllabus-tooltip-popper {
  z-index: 4000 !important;
}
</style>
