import { useCallback, useEffect, useRef } from 'react'
import type { ChatRecord } from '@/types/chat'

type SubmitQuestion = (
  question: string,
  productCode?: string,
  toolId?: string,
  extraParams?: {
    paramMap?: Record<string, string>
    recordId?: string
    recordType?: string
    workFlowSessionId?: string
    isReask?: boolean
    busiType?: string
  },
  workFlowSessionId?: string,
  recordId?: string,
) => void

function tryParseWorkflowDirective(answerText: string): { recordType: string, question?: string } | null {
  const trimmed = (answerText || '').trim()
  if (!trimmed)
    return null
  if (!(trimmed.startsWith('{') && trimmed.endsWith('}')))
    return null
  try {
    const obj = JSON.parse(trimmed)
    if (obj && typeof obj === 'object' && typeof obj.recordType === 'string') {
      return {
        recordType: obj.recordType,
        question: typeof obj.question === 'string' ? obj.question : undefined,
      }
    }
  }
  catch {
    // ignore
  }
  return null
}

export function useBusinessInsightWorkflow(params: {
  enabled: boolean
  toolId: string
  conversationIdRef: React.MutableRefObject<string | undefined>
  items: ChatRecord[]
  onSubmitQuestion: SubmitQuestion
}) {
  const { enabled, toolId, conversationIdRef, items, onSubmitQuestion } = params

  const modeRef = useRef<'main' | 'sub'>('main')

  const startMain = useCallback(() => {
    if (!enabled)
      return
    modeRef.current = 'main'
    // 开启主工作流：不传 question，避免展示用户气泡
    onSubmitQuestion('', undefined, toolId, { recordType: 'A12', busiType: '01' })
  }, [enabled, onSubmitQuestion, toolId])

  // 监听外部事件：点击业务洞察按钮后开启主工作流
  useEffect(() => {
    if (!enabled)
      return

    const handler = (event: CustomEvent) => {
      const { conversationId, toolId: eventToolId } = (event.detail || {}) as any
      if (String(eventToolId ?? '') !== String(toolId))
        return
      if (conversationId && conversationId !== conversationIdRef.current)
        return
      startMain()
    }
    window.addEventListener('startBusinessInsight', handler as EventListener)
    return () => window.removeEventListener('startBusinessInsight', handler as EventListener)
  }, [enabled, startMain, toolId, conversationIdRef])

  // 最小状态机：主流程 answer=JSON → 开启子流程；子流程 end=true → 回主流程
  useEffect(() => {
    if (!enabled)
      return
    const last = [...items].reverse().find(r => r.role === 'ai' && r.answerList?.[0])
    const lastAnswer = last?.answerList?.[0]
    if (!lastAnswer)
      return

    // 只在本轮流式结束后处理，避免边打字边误触发
    if (lastAnswer.endAnswerFlag !== true)
      return

    // 子流程结束回主流程（后端约定：answer.end === true）
    const end = (lastAnswer as any)?.end === true
    if (modeRef.current === 'sub' && end) {
      modeRef.current = 'main'
      const backQuestion = (lastAnswer as any)?.question
      const q = typeof backQuestion === 'string' ? backQuestion.trim() : ''
      if (q) {
        onSubmitQuestion(q, undefined, toolId, { recordType: 'A12', busiType: '01' })
      }
      else {
        onSubmitQuestion('', undefined, toolId, { recordType: 'A12', busiType: '01' })
      }
      return
    }

    // 主流程收到 JSON 指令：开启子流程
    if (modeRef.current === 'main') {
      const directive = tryParseWorkflowDirective(lastAnswer.answer)
      if (directive?.recordType && directive.recordType !== 'A12') {
        modeRef.current = 'sub'
        // 第三步：开启子工作流（不传 question，避免展示用户气泡）
        onSubmitQuestion('', undefined, toolId, { recordType: directive.recordType, busiType: '01' })
      }
    }
  }, [enabled, items, onSubmitQuestion, toolId])

  return {
    startMain,
  }
}
