<template>
  <BaseFlowNode
    :name="nodeData.name ?? ''"
    :number="nodeData.number"
    :description="nodeData.description"
    :description-items="nodeData.descriptionItems"
    :show-content="nodeData.showContent ?? true"
    :selected="Boolean(nodeData.selected)"
    :invalid="Boolean(nodeData.invalid)"
    node-type="action"
    :icon="iconConfig"
    :title-editable="Boolean(!nodeData.isPanMode && !nodeData.readonly)"
    :deletable="!nodeData.readonly"
    @delete="handleDelete"
    @title-edit="handleTitleEdit"
  />
</template>

<script setup lang="ts">
  import { computed, toRef } from 'vue';

  import BaseFlowNode from './baseFlowNode.vue';

  import useX6NodeData from '../../composables/useX6NodeData';
  import { renameFlowByGraphData } from '../../graph/renameRegistry';
  import type { FlowNodeDescriptionItem } from '../../types';
  import type { Node } from '@antv/x6';

  defineOptions({
    name: 'ActionNode',
  });

  interface ActionIconConfig {
    type: string;
    backgroundColor: string;
  }

  const ACTION_TYPE_ICON_MAP: Record<string, ActionIconConfig> = {
    approval: {
      type: 'iconicon_contract',
      backgroundColor: 'var(--warning-yellow)',
    },
  };

  const props = defineProps<{
    node?: Node;
  }>();

  const emit = defineEmits<{
    (event: 'delete'): void;
  }>();

  const { nodeData } = useX6NodeData<{
    kind: 'action';
    nodeId?: string;
    name?: string;
    number?: string;
    description?: string;
    descriptionItems?: FlowNodeDescriptionItem[];
    actionType?: string;
    showContent?: boolean;
    selected?: boolean;
    invalid?: boolean;
    readonly?: boolean;
    isPanMode?: boolean;
  }>(toRef(props, 'node'));

  const iconConfig = computed<ActionIconConfig>(() => {
    const { actionType } = nodeData.value;
    return ACTION_TYPE_ICON_MAP[actionType ?? 'approval'];
  });

  function handleDelete() {
    emit('delete');
  }

  function handleTitleEdit(value: string, done?: () => void) {
    const data = nodeData.value;
    renameFlowByGraphData(data, value);
    props.node?.setData?.({
      ...data,
      name: value,
      invalid: false,
    });
    done?.();
  }
</script>
