import {Background, BackgroundVariant, type NodeProps} from '@xyflow/react'
import {classnames} from 'amis'
import React, {useCallback, useEffect, useMemo} from 'react'
import AddNodeButton from '../component/AddNodeButton.tsx'
import {useDataStore} from '../store/DataStore.ts'
import {flowBackgroundColor, flowDotColor} from '../types.ts'
import AmisNode, {nodeClassName, NormalNodeHandler, outputsFormColumns} from './AmisNode.tsx'

const LoopNode = (props: NodeProps) => {
  const {mergeDataById} = useDataStore()

  useEffect(() => {
    mergeDataById(
      props.id,
      {
        outputs: {
          output: {
            type: 'array-object',
          },
        },
      },
    )
  }, [props.id])

  const columnsSchema = useCallback(() => [
    {
      type: 'switch',
      name: 'failFast',
      label: '快速失败',
      description: '执行过程中一旦出现错误，及时中断循环任务的执行',
    },
    {
      disabled: true,
      type: 'switch',
      name: 'parallel',
      label: '并行执行',
    },
    {
      type: 'divider',
    },
    ...outputsFormColumns(false, true),
  ], [props.id])

  const extraNodeDescription = useMemo(() => {
    return (
      <div className="nodrag relative w-full h-full" style={{minHeight: '211px'}}>
        <Background
          id={`loop-background-${props.id}`}
          className="rounded-xl"
          variant={BackgroundVariant.Cross}
          gap={20}
          size={3}
          style={{
            zIndex: 0,
          }}
          color={flowDotColor}
          bgColor={flowBackgroundColor}
        />
        <AddNodeButton className="mt-2 ml-2" parent={props.id} onlyIcon/>
      </div>
    )
  }, [props.id])

  return (
    <AmisNode
      className={classnames('w-full', 'h-full', nodeClassName('loop'))}
      style={{
        minWidth: '350px',
        minHeight: '290px',
      }}
      nodeProps={props}
      extraNodeDescription={extraNodeDescription}
      columnSchema={columnsSchema}
      handler={<NormalNodeHandler/>}
      resize={{
        minWidth: 350,
        minHeight: 290,
      }}
    />
  )
}

export default React.memo(LoopNode)