<script setup lang="ts">
import type { NodeExecutionResult } from '../components/NodeResultCard.vue';

import { computed, onMounted, onUnmounted, ref, watch } from 'vue';

import { RefreshCw } from '@vben/icons';
import { $t } from '@vben/locales';

import { Handle, Position, useVueFlow } from '@vue-flow/core';

import NodeResultCard from '../components/NodeResultCard.vue';

const props = defineProps(['selected', 'data', 'id']);

const { getNodes, updateNodeInternals, updateNodeData, updateNode } =
  useVueFlow();

// 容器元素引用
const containerRef = ref<HTMLElement | null>(null);
let resizeObserver: null | ResizeObserver = null;

// 使用 ResizeObserver 监听 DOM 尺寸变化
onMounted(() => {
  if (containerRef.value) {
    resizeObserver = new ResizeObserver(() => {
      if (props.id) {
        updateNodeInternals([props.id]);
      }
    });
    resizeObserver.observe(containerRef.value);
  }
});

onUnmounted(() => {
  resizeObserver?.disconnect();
});

// 获取循环模式
const loopMode = computed(() => props.data?.loop_mode || 'for_each');
const loopModeText = computed(() => {
  return loopMode.value === 'for_each'
    ? $t('ai-platform.workflow.nodes.loop.forEach')
    : $t('ai-platform.workflow.nodes.loop.whileLoop');
});

// 获取配置信息
const itemsVariable = computed(() => props.data?.items_variable || '');
const maxIterations = computed(() => props.data?.max_iterations || 100);

// 执行状态
const executionStatus = computed(() => props.data?.executionStatus);
const isRunning = computed(() => executionStatus.value?.status === 'running');
const isSuccess = computed(() => executionStatus.value?.status === 'success');
const isFailed = computed(() => executionStatus.value?.status === 'failed');
const currentIteration = computed(() => executionStatus.value?.iteration ?? 0);
const totalIterations = computed(() => executionStatus.value?.total);

// 执行结果（用于显示日志）
const executionResult = computed<NodeExecutionResult | undefined>(() => {
  return props.data?.executionResult;
});

// 默认最小尺寸
const minWidth = 400;
const minHeight = 350;
const padding = 20;

// 获取子节点列表
const childNodes = computed(() => {
  const allNodes = getNodes.value;
  return allNodes.filter((n) => n.parentNode === props.id);
});

// 子节点数量
const childCount = computed(() => childNodes.value.length);

// 实时计算容器尺寸（根据子节点位置动态调整）
const containerWidth = computed(() => {
  if (childNodes.value.length === 0) {
    return minWidth;
  }

  let maxRight = 0;
  for (const child of childNodes.value) {
    const childWidth = child.dimensions?.width || 280;
    const right = child.position.x + childWidth + padding;
    maxRight = Math.max(maxRight, right);
  }

  return Math.max(minWidth, maxRight);
});

const containerHeight = computed(() => {
  if (childNodes.value.length === 0) {
    return minHeight;
  }

  let maxBottom = 0;
  for (const child of childNodes.value) {
    const childHeight = child.dimensions?.height || 150;
    const bottom = child.position.y + childHeight + padding;
    maxBottom = Math.max(maxBottom, bottom);
  }

  return Math.max(minHeight, maxBottom);
});

// 监听尺寸变化，触发节点内部更新以重新计算连线位置，并同步尺寸到 data 和 style
watch(
  [containerWidth, containerHeight],
  ([width, height]) => {
    if (props.id) {
      // 同步尺寸到 data，供 onDrop 判断使用
      updateNodeData(props.id, { width, height });
      // 设置节点的 style 属性，限制 VueFlow 节点包装元素的尺寸
      updateNode(props.id, {
        style: { width: `${width}px`, height: `${height}px` },
      });
      updateNodeInternals([props.id]);
    }
  },
  { flush: 'post', immediate: true },
);
</script>

<template>
  <div
    ref="containerRef"
    class="loop-container bg-card rounded-xl border shadow-sm transition-all duration-200 hover:shadow-md"
    :class="[
      selected ? 'border-primary ring-primary ring-1' : '',
      isRunning
        ? 'animate-pulse-border !border-blue-500 shadow-lg shadow-blue-500/20 ring-2 ring-blue-500/50'
        : '',
      isSuccess ? '!border-green-500 ring-1 ring-green-500' : '',
      isFailed ? '!border-red-500 ring-2 ring-red-500' : '',
      !selected && !executionStatus?.status ? 'border-border' : '',
    ]"
    :style="{
      width: `${containerWidth}px`,
      height: `${containerHeight}px`,
    }"
  >
    <!-- 循环节点头部 - 与 BaseNode 保持一致的样式 -->
    <div
      class="border-border/50 flex items-center gap-3 rounded-t-xl border-b bg-gradient-to-r from-indigo-50 to-violet-50 px-4 py-3 dark:from-indigo-950 dark:to-violet-950"
    >
      <div
        class="flex size-8 shrink-0 items-center justify-center rounded-lg bg-indigo-200 text-indigo-600 shadow-sm dark:bg-indigo-800 dark:text-indigo-400"
      >
        <RefreshCw class="size-5" :class="{ 'animate-spin': isRunning }" />
      </div>
      <div class="flex flex-1 flex-col overflow-hidden">
        <div class="text-foreground truncate text-sm font-semibold">
          {{ data?.label || $t('ai-platform.workflow.nodes.loop.label') }}
        </div>
        <div class="text-muted-foreground truncate text-[10px]">
          {{ loopModeText }}
        </div>
      </div>
      <!-- 子节点数量 + 运行状态显示 -->
      <div class="flex items-center gap-2">
        <!-- 子节点数量 -->
        <div
          v-if="childCount > 0"
          class="flex items-center rounded border border-indigo-300 bg-indigo-100 px-1.5 py-0.5 text-[10px] text-indigo-600 dark:border-indigo-700 dark:bg-indigo-900 dark:text-indigo-400"
        >
          {{
            $t('ai-platform.workflow.nodes.loop.nodeCount', {
              count: childCount,
            })
          }}
        </div>
        <!-- 运行状态 -->
        <div
          v-if="isRunning"
          class="flex items-center gap-1.5 rounded border border-blue-300 bg-blue-100 px-2 py-0.5 text-[10px] text-blue-600 dark:border-blue-700 dark:bg-blue-900 dark:text-blue-400"
        >
          <span
            class="inline-block size-1.5 animate-pulse rounded-full bg-blue-500"
          ></span>
          <span v-if="totalIterations">{{
            $t('ai-platform.workflow.nodes.loop.iteration', {
              current: currentIteration + 1,
              total: totalIterations,
            })
          }}</span>
          <span v-else>{{
            $t('ai-platform.workflow.nodes.loop.iterationNoTotal', {
              current: currentIteration + 1,
            })
          }}</span>
        </div>
        <div
          v-else
          class="text-muted-foreground bg-muted border-border flex items-center rounded border px-1.5 py-0.5 text-[10px]"
        >
          {{
            $t('ai-platform.workflow.nodes.loop.maxIterations', {
              max: maxIterations,
            })
          }}
        </div>
      </div>
    </div>

    <!-- 循环配置信息 -->
    <div
      class="border-border/50 text-muted-foreground space-y-1 border-b px-4 py-2 text-xs"
    >
      <div class="flex items-center justify-between">
        <span>{{
          loopMode === 'for_each'
            ? $t('ai-platform.workflow.nodes.loop.forEach')
            : $t('ai-platform.workflow.nodes.loop.loopCondition')
        }}</span>
        <span
          v-if="loopMode === 'for_each' && itemsVariable"
          class="max-w-[150px] truncate font-mono text-indigo-600 dark:text-indigo-400"
        >
          {{ itemsVariable }}
        </span>
        <span
          v-else-if="loopMode === 'while'"
          class="text-indigo-600 dark:text-indigo-400"
        >
          {{ $t('ai-platform.workflow.nodes.loop.whileLoop') }}
        </span>
        <span v-else class="text-muted-foreground">{{
          $t('ai-platform.workflow.nodes.common.notConfigured')
        }}</span>
      </div>
      <div v-if="loopMode === 'for_each'" class="text-muted-foreground">
        {{ $t('ai-platform.workflow.nodes.loop.availableVariables') }}
        <code class="bg-muted rounded px-1 text-indigo-600 dark:text-indigo-400">item</code>
        <code class="bg-muted rounded px-1 text-indigo-600 dark:text-indigo-400">index</code>
      </div>
    </div>

    <!-- 循环体区域（子节点容器） -->
    <div
      class="loop-body relative p-4"
      :style="{ height: `${containerHeight - 120}px` }"
    >
      <div
        v-if="childCount === 0"
        class="border-border bg-muted/30 text-muted-foreground flex h-full min-h-[80px] items-center justify-center rounded-lg border-2 border-dashed text-sm"
      >
        {{ $t('ai-platform.workflow.nodes.loop.dragNodeHere') }}
      </div>
    </div>

    <!-- 输入 Handle -->
    <Handle
      type="target"
      :position="Position.Left"
      id="target"
      class="!bg-primary !h-3 !w-3 !border-2 !border-white transition-transform hover:scale-125"
      :style="{ top: '28px' }"
    />

    <!-- 输出 Handle -->
    <Handle
      type="source"
      :position="Position.Right"
      id="source"
      class="!bg-primary !h-3 !w-3 !border-2 !border-white transition-transform hover:scale-125"
      :style="{ top: '28px' }"
    />

    <!-- 节点下方的执行结果卡片（独立显示，不在节点内部） -->
    <NodeResultCard
      v-if="executionResult"
      :result="executionResult"
      node-type="loop"
      class="mt-3"
      :style="{ width: `${containerWidth}px` }"
    />
  </div>
</template>

<style scoped>
.loop-container {
  position: relative;
  z-index: 0;
  /* 确保节点尺寸与 VueFlow 计算的尺寸一致 */
  box-sizing: border-box;
  overflow: visible;
}

.loop-body {
  background: repeating-linear-gradient(
    45deg,
    transparent,
    transparent 10px,
    hsl(var(--muted) / 0.3) 10px,
    hsl(var(--muted) / 0.3) 20px
  );
  pointer-events: none;
  overflow: hidden;
}

.loop-body > * {
  pointer-events: auto;
}
</style>
