import React, { createContext, useReducer, Dispatch } from 'react'
import reducer from './reducer'
import { Actions } from '../enum'
import type { Elements, OnLoadParams } from 'react-flow-renderer'
import { transformElements } from '@/components/Flow/src/shared/transformer'
import { FlowTreeNode } from '@/components/Flow/src/type'
import { DrawerAction } from '@/components/Drawer'

export type FlowContextState = {
  dataID: string
  process: FlowTreeNode[]
  elements: Elements
  flowInstance?: OnLoadParams
  drawer: DrawerAction
  executorList: API.ExecutorItem[]
  matterList: any[]
}
type FlowContextProviderProps = {
  children: React.ReactNode
  initialProcess: Elements
  dataID: string
  executorList: API.ExecutorItem[]
  matterList: any[]
}

export type DispatchAction = Dispatch<{
  type: `${Actions}`
  payload: any
}>

const FlowContext = createContext<{ flowStore: FlowContextState; dispatch: DispatchAction }>({})

const FlowContextProvider: React.FC<FlowContextProviderProps> = props => {
  const { children, initialProcess = [], dataID, executorList = [], matterList = [] } = props
  const [flowStore, dispatch] = useReducer(reducer, {
    process: initialProcess,
    elements: transformElements(initialProcess),
    dataID,
    executorList,
    matterList
  })
  return <FlowContext.Provider value={{ flowStore, dispatch }}>{children}</FlowContext.Provider>
}

export { FlowContext, FlowContextProvider, Actions }
