'use client'
import React, { useEffect, useMemo } from 'react'
import * as R from 'ramda'
import { useAtom, useAtomValue } from 'jotai'
import { asideInstantAtomFamily, asideInstantAtomsAtom, curNodeAtom } from '../store'
import Agent from './ASideType/Agent'
import Form from './ASideType/Form'
import Unsupport from './ASideType/Unsupport'

const ASide = () => {
  const node = useAtomValue(curNodeAtom)

  const Comp = useMemo(() => {
    return R.cond([
      [R.propEq('form_card', 'type'), R.always(Form)],
      [R.propEq('UserTask', 'type'), R.always(Agent)],
      [R.T, R.always(Unsupport)],
    ])(node)
  }, [node, node?.id])

  // 动态注册当前节点的Atom，并将其放进一个atom集合的atom，方便后续格式化所有节点实例
  const asideInstantAtom = asideInstantAtomFamily(node?.id)
  const [, dispatchAsideInstantAtoms] = useAtom(asideInstantAtomsAtom)
  useEffect(() => {
    if (node?.id) {
      dispatchAsideInstantAtoms({ [node.id]: asideInstantAtom })
    }
  }, [asideInstantAtom])

  return (
    <div className="shadow-xl rounded-box shrink-0 basis-[350px] p-2">
      <Comp key={node?.id} node={node} asideInstantAtom={asideInstantAtom}></Comp>
    </div>
  )
}
export default React.memo(React.forwardRef(ASide))