import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { Button, Skeleton } from '@heroui/react'
import type { Answer } from '@/types/chat'
import { fetchOrderQueryRecommendQuestion } from '@/api/chat'
import { findToolRowBySessionToolId, getRecommendRecordTypeForToolRow, readToolListFromSessionStorage } from '@/lib/toolRoleRecordTypes'
import SendIcon from '@/assets/svg/sendBlack.svg?react'

interface ChatAnswerRecommendProps {
  answer: Answer
  onSubmitQuestion: (question: string) => void
  onLoadingChange?: (loading: boolean) => void
}
export const ChatAnswerRecommend: React.FC<ChatAnswerRecommendProps> = ({ answer, onSubmitQuestion, onLoadingChange }) => {
  let isGet = false
  const [questionList, setQuestionList] = useState<string[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [searchParams] = useSearchParams()
  const getAnswerRecommend = async () => {
    // 若回答内容包含以下关键字，则不再请求推荐问题接口
    const content = answer?.answer || ''
    const blockKeywords = ['抱歉', 'LLM响应异常', 'QPM最大流量限制', '请求时间超时', '该请求超出我的响应范围']
    const shouldBlock = blockKeywords.some(keyword => content.includes(keyword))
    if (shouldBlock) {
      onLoadingChange?.(false)
      return
    }

    setLoading(true)
    onLoadingChange?.(true)
    // 从 sessionStorage 中获取 toolId
    const toolId = typeof window !== 'undefined' ? sessionStorage.getItem('currentToolId') : null
    const from = searchParams.get('from')
    const place = searchParams.get('place')
    let busiType: string | undefined
    let recordType: string | undefined

    // 策略场景
    if (from === 'tactics') {
      busiType = '02'
      if (place === 'user') {
        recordType = 'A20'
      }
      else if (place === 'order') {
        recordType = 'A13'
      }
      else {
        recordType = 'A19'
      }
    }
    else {
      const list = readToolListFromSessionStorage()
      const row = findToolRowBySessionToolId(list, toolId || '')
      const rt = getRecommendRecordTypeForToolRow(row)
      if (rt) {
        busiType = '01'
        recordType = rt
      }
    }

    try {
      const res = await fetchOrderQueryRecommendQuestion(
        answer.conversationId || '',
        answer.recordId || '',
        toolId || undefined,
        busiType,
        recordType,
      )
      if (res.ok) {
        setQuestionList(res.data.questionList)
      }
    }
    finally {
      setLoading(false)
      onLoadingChange?.(false)
    }
  }

  useEffect(() => {
    if (!isGet) {
      isGet = true

      if (typeof window === 'undefined') {
        return
      }

      const shouldSkipFetch = sessionStorage.getItem('showToolQuestion') === 'true'
      if (!shouldSkipFetch) {
        // 正常问答模式：发起推荐问题请求，并通过 onLoadingChange 通知外层 loading 状态
        getAnswerRecommend()
      }
      else {
        // 工具问答模式：跳过推荐问题请求，直接告知外层无需等待
        onLoadingChange?.(false)
      }
    }
  }, [])
  return (
    <div className="sm:pl-[62px] mt-[12px] flex flex-col sm:max-w-[700px] md:max-w-[900px] lg:max-w-[1200px]">
      {!loading && questionList.length !== 0 && questionList.length > 0 && (
        <div className="flex flex-col gap-[8px]">
          {
            questionList.map(item => (
              <Button onPress={() => onSubmitQuestion(item)} key={item} color="primary" variant="light" className="text-left bg-[#fff] w-fit max-w-full text-[#333] rounded-[8px] data-[hover=true]:bg-[#F6F6F8] data-[hover=true]:text-[#333]">
                <div className="w-full sm:w-full text-nowrap text-ellipsis overflow-hidden">
                  {item}
                </div>
                <SendIcon />
              </Button>
            ))
          }
        </div>
      )}
      {
        loading && questionList && questionList.length === 0 && (
          <div className="flex flex-col gap-[8px]">
            <Skeleton className="w-2/3 sm:w-[300px] rounded-lg">
              <div className="h-[40px] w-full rounded-lg bg-[#fff]"></div>
            </Skeleton>
            <Skeleton className="w-3/4 sm:w-[300px] rounded-lg">
              <div className="h-[40px] w-full rounded-lg bg-[#fff]"></div>
            </Skeleton>
          </div>
        )
      }
    </div>
  )
}
