'use client';

import React, { useEffect, useMemo } from 'react'
import { BsArrowLeft, BsArrowRight } from "react-icons/bs";
import Agent from './NodeType/Agent';
import Form from './NodeType/Form';
import Unsupport from './NodeType/Unsupport';
import * as R from 'ramda'
import { curNodeAtom, curStepAtom, arrowStateAtom, cardInstantAtomFamily, cardInstantAtomsAtom } from '../store';
import { useAtom, useAtomValue } from 'jotai';

const NodeRender = () => {
  const [curStep, setCurStep] = useAtom(curStepAtom)
  const node = useAtomValue(curNodeAtom)
  const arrowState = useAtomValue(arrowStateAtom)
  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])
  const nodeName = useMemo(() => {
    return R.cond([
      [R.propEq('form_card', 'type'), R.always('表单填写')],
      [R.propEq('UserTask', 'type'), R.pathOr('Unknown Agent', ['properties', 'item', 'assistantName'])],
      [R.T, R.always('Unknown')],
    ])(node)
  }, [node, node?.id])

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


  const onNextStep = () => {
    setCurStep(prev => prev + 1)
  }

  const onPrevStep = () => {
    setCurStep(prev => prev - 1)
  }

  return (
    <div className="card card-compact shadow-xl flex-1 overflow-hidden">
      <div className="card-body overflow-hidden">
        <div className="card-title rounded-box bg-slate-200 p-2">
          <h2 className="flex-1">
            {curStep + 1}: {nodeName}
          </h2>
          <button className='btn btn-circle btn-sm' disabled={!arrowState.prev} onClick={onPrevStep}><BsArrowLeft /></button>
          <button className='btn btn-circle btn-sm' disabled={!arrowState.next} onClick={onNextStep}><BsArrowRight /></button>
        </div>
        <div className="flex-1 flex flex-col items-stretch overflow-auto">
          <Comp key={node?.id} node={node} cardInstantAtom={cardInstantAtom}></Comp>
        </div>
        {/* <div className="card-actions justify-end">
          <button className="btn btn-primary">确认，下一步</button>
        </div> */}
      </div>
    </div>
  )
}

export default React.memo(React.forwardRef(NodeRender))