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
}
export const ChatAnswerRecommend: React.FC<ChatAnswerRecommendProps> = ({ answer, onSubmitQuestion }) => {
  let isGet = false
  const [questionList, setQuestionList] = useState<string[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const getAnswerRecommend = async () => {
    setLoading(true)
    // 从 sessionStorage 中获取 toolId
    const toolId = typeof window !== 'undefined' ? sessionStorage.getItem('currentToolId') : null
    const res = await fetchQueryRecommendQuestion(
      answer.conversationId || '',
      answer.recordId || '',
      toolId || undefined,
    )
    if (res.ok) {
      setQuestionList(res.data.questionList)
    }
    setLoading(false)
  }

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

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

      const shouldSkipFetch = sessionStorage.getItem('showToolQuestion') === 'true'
      if (shouldSkipFetch) {
        return // skip calling recommend API when tool question mode is enabled
      }

      getAnswerRecommend()
    }
  }, [])
  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>
  )
}
