import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { Button, Skeleton } from '@heroui/react'
import type { Answer } from '@/types/chat'
import { fetchQueryRecommendQuestion } from '@/api/chat'
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 () => {
    setLoading(true)
    onLoadingChange?.(true)
    // 从 sessionStorage 中获取 toolId
    const toolId = typeof window !== 'undefined' ? sessionStorage.getItem('currentToolId') : null
    // 仅在 from=tactics 场景下，按照要求补充 busiType / recordType 参数
    const from = searchParams.get('from')
    const place = searchParams.get('place')
    const fromValues = searchParams.getAll('from')
    const shouldAttachBusiParams = from === 'tactics'
    const busiType = shouldAttachBusiParams ? '02' : undefined
    let recordType: string | undefined
    if (shouldAttachBusiParams) {
      // from=tactics 且 from=order → recordType=A11
      // from=tactics 且 place=user → recordType=A03
      // from=tactics 且 place!=user/无 → recordType=A01
      if (fromValues.includes('order')) {
        recordType = 'A11'
      }
      else if (place === 'user') {
        recordType = 'A03'
      }
      else {
        recordType = 'A01'
      }
    }
    try {
      const res = await fetchQueryRecommendQuestion(
        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">
      {!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>
  )
}
