import {PlusCircleFilled, RollbackOutlined, SaveFilled} from '@ant-design/icons'
import {
  Background,
  BackgroundVariant,
  Controls,
  type Edge,
  MiniMap,
  type Node,
  type NodeProps,
  ReactFlow,
} from '@xyflow/react'
import type {Schema} from 'amis'
import {Button, Drawer, Dropdown, message, Popconfirm, Space} from 'antd'
import {arrToMap, find, isEqual, isNil, randomId} from 'licia'
import {type JSX, type MemoExoticComponent, useEffect, useState} from 'react'
import {useNavigate} from 'react-router'
import styled from 'styled-components'
import '@xyflow/react/dist/style.css'
import {useShallow} from 'zustand/react/shallow'
import {amisRender, commonInfo, horizontalFormOptions} from '../../util/amis.tsx'
import {checkAddConnection, checkAddNode, checkSave} from './FlowChecker.tsx'
import CodeNode from './node/CodeNode.tsx'
import KnowledgeNode from './node/KnowledgeNode.tsx'
import LlmNode from './node/LlmNode.tsx'
import OutputNode from './node/OutputNode.tsx'
import SwitchNode from './node/SwitchNode.tsx'
import {useContextStore} from './store/ContextStore.ts'
import {useDataStore} from './store/DataStore.ts'
import {useFlowStore} from './store/FlowStore.ts'

const FlowableDiv = styled.div`
    height: 100%;

    .react-flow__node.selectable {
        &:focus {
            box-shadow: 0 0 20px 1px #e8e8e8;
            border-radius: 8px;
        }
    }

    .react-flow__handle.connectionindicator {
        width: 10px;
        height: 10px;
        background-color: #ffffff;
        border: 1px solid #000000;

        &:hover {
            background-color: #e8e8e8;
            border: 1px solid #c6c6c6;
        }
    }

    .toolbar {
        position: absolute;
        right: 20px;
        top: 20px;
        z-index: 10;
    }

    .node-card {
        cursor: default;

        .card-container {
        }
    }
`

export type GraphData = { nodes: Node[], edges: Edge[], data: any }

export type FlowEditorProps = {
  inputSchema: Record<string, Record<string, any>>,
  graphData: GraphData,
  onGraphDataChange: (graphData: GraphData) => void,
}

function FlowEditor(props: FlowEditorProps) {
  const navigate = useNavigate()
  const [messageApi, contextHolder] = message.useMessage()
  const [nodeDef] = useState<{
    key: string,
    name: string,
    component: MemoExoticComponent<(props: NodeProps) => JSX.Element>
  }[]>([
    {
      key: 'output-node',
      name: '输出',
      component: OutputNode,
    },
    {
      key: 'llm-node',
      name: '大模型',
      component: LlmNode,
    },
    {
      key: 'knowledge-node',
      name: '知识库',
      component: KnowledgeNode,
    },
    {
      key: 'code-node',
      name: '代码执行',
      component: CodeNode,
    },
    {
      key: 'switch-node',
      name: '条件分支',
      component: SwitchNode,
    },
  ])
  const [open, setOpen] = useState(false)

  const {data, setData, getDataById, setDataById} = useDataStore(
    useShallow(state => ({
      data: state.data,
      setData: state.setData,
      getDataById: state.getDataById,
      setDataById: state.setDataById,
    })),
  )
  const {
    nodes,
    addNode,
    setNodes,
    onNodesChange,
    edges,
    setEdges,
    onEdgesChange,
    onConnect,
  } = useFlowStore(
    useShallow(state => ({
      nodes: state.nodes,
      getNodes: state.getNodes,
      addNode: state.addNode,
      removeNode: state.removeNode,
      setNodes: state.setNodes,
      onNodesChange: state.onNodesChange,
      edges: state.edges,
      getEdges: state.getEdges,
      setEdges: state.setEdges,
      onEdgesChange: state.onEdgesChange,
      onConnect: state.onConnect,
    })),
  )

  const {
    setInputSchema,
  } = useContextStore()

  const [currentNodeForm, setCurrentNodeForm] = useState<JSX.Element>()
  const editNode = (id: string, columnSchema?: Schema[]) => {
    if (!isNil(columnSchema)) {
      setCurrentNodeForm(
        amisRender(
          {
            type: 'wrapper',
            size: 'none',
            body: [
              {
                debug: commonInfo.debug,
                type: 'form',
                ...horizontalFormOptions(),
                wrapWithPanel: false,
                onEvent: {
                  submitSucc: {
                    actions: [
                      {
                        actionType: 'custom',
                        // @ts-ignore
                        script: (context, action, event) => {
                          setDataById(
                            id,
                            {
                              ...context.props.data,
                              finished: true,
                            },
                          )
                          setOpen(false)
                        },
                      },
                    ],
                  },
                },
                body: [
                  ...(columnSchema ?? []),
                  {
                    type: 'wrapper',
                    size: 'none',
                    className: 'space-x-2 text-right',
                    body: [
                      {
                        type: 'action',
                        label: '取消',
                        onEvent: {
                          click: {
                            actions: [
                              {
                                actionType: 'custom',
                                // @ts-ignore
                                script: (context, action, event) => {
                                  setOpen(false)
                                },
                              },
                            ],
                          },
                        },
                      },
                      {
                        type: 'submit',
                        label: '保存',
                        level: 'primary',
                      },
                    ],
                  },
                ],
              },
            ],
          },
          getDataById(id),
        ),
      )
      setOpen(true)
    }
  }

  // 用于透传node操作到主流程
  const initialNodeHandlers = {
    editNode,
  }

  useEffect(() => {
    // language=JSON
    // let initialData = JSON.parse('{"nodes":[{"id":"TCxPixrdkI","type":"start-node","position":{"x":-256,"y":109.5},"data":{},"measured":{"width":256,"height":83},"selected":false,"dragging":false},{"id":"tGs78_ietp","type":"llm-node","position":{"x":108,"y":-2.5},"data":{},"measured":{"width":256,"height":105},"selected":false,"dragging":false},{"id":"OeZdaU7LpY","type":"llm-node","position":{"x":111,"y":196},"data":{},"measured":{"width":256,"height":105},"selected":false,"dragging":false},{"id":"LjfoCYZo-E","type":"knowledge-node","position":{"x":497.62196259607214,"y":-10.792497317791003},"data":{},"measured":{"width":256,"height":75},"selected":false,"dragging":false},{"id":"sQM_22GYB5","type":"end-node","position":{"x":874.3164534765615,"y":151.70316541496913},"data":{},"measured":{"width":256,"height":75},"selected":false,"dragging":false},{"id":"KpMH_xc3ZZ","type":"llm-node","position":{"x":529.6286840434341,"y":150.4721376669937},"data":{},"measured":{"width":256,"height":75},"selected":false,"dragging":false},{"id":"pOrR6EMVbe","type":"switch-node","position":{"x":110.33793030183864,"y":373.9551529987239},"data":{},"measured":{"width":256,"height":157},"selected":false,"dragging":false}],"edges":[{"source":"TCxPixrdkI","sourceHandle":"source","target":"tGs78_ietp","targetHandle":"target","id":"xy-edge__TCxPixrdkIsource-tGs78_ietptarget"},{"source":"TCxPixrdkI","sourceHandle":"source","target":"OeZdaU7LpY","targetHandle":"target","id":"xy-edge__TCxPixrdkIsource-OeZdaU7LpYtarget"},{"source":"tGs78_ietp","sourceHandle":"source","target":"LjfoCYZo-E","targetHandle":"target","id":"xy-edge__tGs78_ietpsource-LjfoCYZo-Etarget"},{"source":"LjfoCYZo-E","sourceHandle":"source","target":"KpMH_xc3ZZ","targetHandle":"target","id":"xy-edge__LjfoCYZo-Esource-KpMH_xc3ZZtarget"},{"source":"OeZdaU7LpY","sourceHandle":"source","target":"KpMH_xc3ZZ","targetHandle":"target","id":"xy-edge__OeZdaU7LpYsource-KpMH_xc3ZZtarget"},{"source":"KpMH_xc3ZZ","sourceHandle":"source","target":"sQM_22GYB5","targetHandle":"target","id":"xy-edge__KpMH_xc3ZZsource-sQM_22GYB5target"},{"source":"TCxPixrdkI","sourceHandle":"source","target":"pOrR6EMVbe","id":"xy-edge__TCxPixrdkIsource-pOrR6EMVbe"},{"source":"pOrR6EMVbe","sourceHandle":"3","target":"sQM_22GYB5","targetHandle":"target","id":"xy-edge__pOrR6EMVbe3-sQM_22GYB5target"},{"source":"pOrR6EMVbe","sourceHandle":"1","target":"KpMH_xc3ZZ","targetHandle":"target","id":"xy-edge__pOrR6EMVbe1-KpMH_xc3ZZtarget"}],"data":{"tGs78_ietp":{"model":"qwen3","outputs":{"text":{"type":"string"}},"systemPrompt":"你是个聪明人"},"OeZdaU7LpY":{"model":"qwen3","outputs":{"text":{"type":"string"}},"systemPrompt":"你也是个聪明人"}}}')
    // let initialData: any = {}
    let initialNodes = props.graphData?.nodes ?? []
    let initialEdges = props.graphData?.edges ?? []

    let initialNodeData = props.graphData?.data ?? {}
    setData(initialNodeData)

    for (let node of initialNodes) {
      node.data = initialNodeHandlers
    }
    setNodes(initialNodes)
    setEdges(initialEdges)

    setInputSchema(props.inputSchema)
  }, [props.graphData])

  return (
    <FlowableDiv>
      {contextHolder}
      <Space className="toolbar">
        <Dropdown
          menu={{
            items: nodeDef.map(def => ({key: def.key, label: def.name})),
            onClick: ({key}) => {
              try {
                if (commonInfo.debug) {
                  console.info('Add', key, JSON.stringify({nodes, edges, data}))
                }
                checkAddNode(key, nodes, edges)
                addNode({
                  id: randomId(10),
                  type: key,
                  position: {x: 100, y: 100},
                  data: initialNodeHandlers,
                })
              } catch (e) {
                // @ts-ignore
                messageApi.error(e.toString())
              }
            },
          }}
        >
          <Button type="default">
            <PlusCircleFilled/>
            新增节点
          </Button>
        </Dropdown>
        <Popconfirm
          title="返回上一页"
          description="未保存的流程图将会被丢弃，确认是否返回"
          onConfirm={() => navigate(-1)}
        >
          <Button type="default">
            <RollbackOutlined/>
            返回
          </Button>
        </Popconfirm>
        <Button type="primary" onClick={() => {
          try {
            if (commonInfo.debug) {
              console.info('Save', JSON.stringify({nodes, edges, data}))
            }
            checkSave(nodes, edges, data)
            props.onGraphDataChange({nodes, edges, data})
          } catch (e) {
            // @ts-ignore
            messageApi.error(e.toString())
          }
        }}>
          <SaveFilled/>
          保存
        </Button>
      </Space>
      <Drawer
        title="节点编辑"
        open={open}
        closeIcon={false}
        maskClosable={false}
        destroyOnHidden
        size="large"
      >
        {currentNodeForm}
      </Drawer>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={(connection) => {
          try {
            if (commonInfo.debug) {
              console.info('Connection', JSON.stringify(connection), JSON.stringify({nodes, edges, data}))
            }
            checkAddConnection(connection, nodes, edges)
            onConnect(connection)
          } catch (e) {
            // @ts-ignore
            messageApi.error(e.toString())
          }
        }}
        // @ts-ignore
        nodeTypes={arrToMap(
          nodeDef.map(def => def.key),
          key => find(nodeDef, def => isEqual(key, def.key))!.component)
        }
      >
        <Controls/>
        <MiniMap/>
        <Background variant={BackgroundVariant.Cross} gap={20} size={3}/>
      </ReactFlow>
    </FlowableDiv>
  )
}

export default FlowEditor