import { useEffect, useState } from 'react'
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 getAnswerRecommend = async () => {
    setLoading(true)
    onLoadingChange?.(true)
    // 从 sessionStorage 中获取 toolId
    const toolId = typeof window !== 'undefined' ? sessionStorage.getItem('currentToolId') : null
    try {
      const res = await fetchQueryRecommendQuestion(
        answer.conversationId || '',
        answer.recordId || '',
        toolId || undefined,
      )
      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>
  )
}
