import {RollbackOutlined, SaveFilled} from '@ant-design/icons'
import {Background, BackgroundVariant, Controls, MiniMap, Panel, ReactFlow} from '@xyflow/react'
import {Button, message, Popconfirm, Space} from 'antd'
import {arrToMap} from 'licia'
import {useEffect} from 'react'
import {useNavigate} from 'react-router'
import styled from 'styled-components'
import '@xyflow/react/dist/style.css'
import {commonInfo} from '../../util/amis.tsx'
import {checkAddConnection, checkSave} from './FlowChecker.tsx'
import {useNodeDrag} from './Helper.tsx'
import {NodeRegistryMap} from './NodeRegistry.tsx'
import {useContextStore} from './store/ContextStore.ts'
import {useDataStore} from './store/DataStore.ts'
import {useFlowStore} from './store/FlowStore.ts'
import {flowDotColor, type FlowEditorProps} from './types.ts'
import AddNodeButton from './component/AddNodeButton.tsx'

const FlowableDiv = styled.div`
    .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;
        }
    }

    .node-card {
        cursor: default;

        .card-container {
        }
    }
`

function FlowEditor(props: FlowEditorProps) {
  const navigate = useNavigate()
  const [messageApi, contextHolder] = message.useMessage()

  const {data, setData, setDataById} = useDataStore()
  const {
    nodes,
    addNode,
    setNodes,
    onNodesChange,
    edges,
    setEdges,
    onEdgesChange,
    onConnect,
  } = useFlowStore()

  const {inputSchema, setInputSchema} = useContextStore()

  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)
    setNodes(initialNodes)
    setEdges(initialEdges)

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

  const {
    onNodeDragStart,
    onNodeDrag,
    onNodeDragEnd,
  } = useNodeDrag([props.graphData])

  return (
    <FlowableDiv className="h-full w-full">
      {contextHolder}
      <ReactFlow
        className="rounded-xl"
        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(Object.keys(NodeRegistryMap), key => NodeRegistryMap[key]!.component)}
        onNodeDragStart={onNodeDragStart}
        onNodeDrag={onNodeDrag}
        onNodeDragStop={onNodeDragEnd}
      >
        <Panel position="top-right">
          <Space className="toolbar">
            <AddNodeButton/>
            <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(inputSchema, nodes, edges, data)
                props.onGraphDataChange({nodes, edges, data})
              } catch (e) {
                // @ts-ignore
                messageApi.error(e.toString())
              }
            }}>
              <SaveFilled/>
              保存
            </Button>
          </Space>
        </Panel>
        <Controls/>
        <MiniMap/>
        <Background
          variant={BackgroundVariant.Cross}
          gap={20}
          size={3}
          color={flowDotColor}
        />
      </ReactFlow>
    </FlowableDiv>
  )
}

export default FlowEditor