import {PlusCircleFilled} from '@ant-design/icons'
import {Button, Dropdown, message} from 'antd'
import type {ButtonProps} from 'antd/lib'
import {isEqual, randomId, unique} from 'licia'
import {commonInfo} from '../../../util/amis.tsx'
import {checkAddNode} from '../FlowChecker.tsx'
import {NodeRegistry, NodeRegistryMap} from '../NodeRegistry.tsx'
import {useDataStore} from '../store/DataStore.ts'
import {useFlowStore} from '../store/FlowStore.ts'

export type AddNodeButtonProps = ButtonProps & {
  parent?: string
  onlyIcon?: boolean
}

const AddNodeButton = (props: AddNodeButtonProps) => {
  const {data, setDataById} = useDataStore()
  const {nodes, addNode, edges} = useFlowStore()
  return (
    <Dropdown
      menu={{
        items: unique(NodeRegistry.map(i => i.group))
          .map(group => ({
            type: 'group',
            label: group,
            children: NodeRegistry
              .filter(i => isEqual(group, i.group))
              // 循环节点里不能再嵌套循环节点
              .filter(i => !props.parent || (props.parent && !isEqual(i.key, 'loop-node')))
              .map(i => ({key: i.key, label: i.name, icon: i.icon})),
          })),
        onClick: ({key}) => {
          try {
            if (commonInfo.debug) {
              console.info('Add', key, JSON.stringify({nodes, edges, data}))
            }
            checkAddNode(key, props.parent, nodes, edges)

            let nodeId = randomId(10, 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM')
            let define = NodeRegistryMap[key]

            setDataById(
              nodeId,
              {
                node: {
                  name: define.name,
                  description: define.description,
                },
              },
            )

            addNode({
              id: nodeId,
              type: key,
              position: {x: 50, y: 130},
              data: {},
              // 如果是循环节点就将节点加入到循环节点中
              ...(props.parent ? {
                parentId: props.parent,
                extent: 'parent',
              } : {}),
            })
          } catch (e) {
            // @ts-ignore
            message.error(e.toString())
          }
        },
      }}
    >
      <Button {...props}>
        <PlusCircleFilled/>
        {props.onlyIcon ? undefined : '新增节点'}
      </Button>
    </Dropdown>
  )
}

export default AddNodeButton
