import { Avatar, Spinner } from '@nextui-org/react'
import { motion } from 'framer-motion'
import { useState } from 'react'
import { ChatAnswerShower } from './ChatAnswerShower'
import { ChatAnswerParser } from './ChatAnswerParser'
import { ChatAnswerRecommend } from './ChatAnswerRecommend'
import type { Answer, ChatRecord } from '@/types/chat'
import AvatarBot from '@/assets/avatarBot.png'
import { useAppDispatch } from '@/store/hook'
import { setIsAsking } from '@/store/chatSlice'

interface ChatAnswerBoxProps {
  record: ChatRecord
  showIndex: number
  isLastAnswer: boolean
  index: number
  onSubmitQuestion: (question: string) => void
}

export const ChatAnswerBox: React.FC<ChatAnswerBoxProps> = ({ record, showIndex, isLastAnswer, onSubmitQuestion }) => {
  const [isShowRecommend, setIsShowRecommend] = useState(false)
  const [recommendUseAnswer, setRecommendUseAnswer] = useState<Answer>()
  const dispatch = useAppDispatch()

  const handleComplate = (answer: Answer) => {
    setIsShowRecommend(true)
    setRecommendUseAnswer(answer)
    dispatch(setIsAsking(false))
  }
  return (
    <div>
      {record.answerList.map((item, index) => {
        return (
          index === showIndex && (
            <div className="chatItemBotContainer w-full" key={`${item.recordId}-${index}`}>
              <div className="flex">
                <Avatar className="flex-shrink-0" src={AvatarBot} />
                <motion.div
                  className="ml-[20px] bg-white rounded-[20px] box-border px-[24px] py-[20px]"
                >
                  {item.answer && (
                    <div className="content">
                      {item.isShow && <ChatAnswerShower answer={item} />}
                      {!item.isShow && <ChatAnswerParser onComplate={() => handleComplate(item)} answer={item} />}
                    </div>
                  )}
                  {!item.answer && (
                    <Spinner size="sm" />
                  )}
                </motion.div>
                <div className="w-[130px]"></div>
              </div>
              {isLastAnswer
              && isShowRecommend
              && recommendUseAnswer
              && <ChatAnswerRecommend onSubmitQuestion={onSubmitQuestion} answer={recommendUseAnswer} />}
              <div className="h-[32px] w-full"></div>
            </div>
          )
        )
      })}
    </div>
  )
}
