import { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import HelloGIF from '@/assets/img/hello.gif';
import style from './index.module.less';
import WhatsThing from '@/assets/img/whatsThing.png';
import CircleIcon from '@/assets/img/circle.png';
import RightIcon from '@/assets/img/right.png';


import { setInitMsg } from '@/store/slices/room';
import { requestGetMethod } from '@/app/base';


type Props = {
    toRoom:() => Promise<void>
}

export default function HeaderGroup({toRoom}:Props) {
  const [isRotating, setIsRotating] = useState(false);
  const [displayQuestions, setDisplayQuestions] = useState<string[]>([]);
  const [allQuestions,setAllQuestions] = useState<string[]>([])

  // 随机获取4个问题的函数
  const getRandomQuestions = () => {
    const _allQuestions = Array.from(allQuestions)
    const result: string[] = [];
    const questionCount = Math.min(4, _allQuestions.length);
    
    for (let i = 0; i < questionCount; i++) {
      const randomIndex = Math.floor(Math.random() * _allQuestions.length);
      result.push(_allQuestions.splice(randomIndex, 1)[0]);
    }
    
    return result;
  };

  const getQuestion = async() => {
    const queryData = await requestGetMethod(`https://api.v3.ycymedu.com/api/zhiYuan/aigcquestionswords?`,true)()
    const res = await queryData?.json();
    if(res.code === 200){
        setAllQuestions(res.result)
       
    }
  }

  useEffect(() => {
    setDisplayQuestions(getRandomQuestions());
  },[allQuestions])

  // 组件初始化时获取随机问题
  useEffect(() => {
    getQuestion();  
   
  }, []);

  const handleClick = () => {
    setIsRotating(true);
    
    // 更新随机问题
    setDisplayQuestions(getRandomQuestions());

    // 动画结束后重置状态
    setTimeout(() => {
      setIsRotating(false);
    }, 1000); 
  };

  const dispatch = useDispatch();
  const handleQuestion = async(question: string) => {
    await toRoom();

    dispatch(
        setInitMsg(question)
    );

  };

  return (
    <div className={style.headerWrapper}>
      <div className={style.wrapper}>
        <img className={style.img} src={HelloGIF} alt="hello" />
        <div className={style.text}>Hey，我是您的六纬AI小助手</div>
      </div>
      <div className={style['main-wrapper']}>
        <div className={style.main} onClick={handleClick}>
          <img className={style.thing} src={WhatsThing} alt="whatsThing" />
          <div className={style.circle}>
            <img src={CircleIcon} className={isRotating ? style.rotating : ''} alt="circle" />
            <div className='change'>换一批</div>
          </div>
        </div>
        {displayQuestions.map((item, index) => (
          <div className={style.tip} key={index} onClick={() =>handleQuestion(item)}>
            <div>{item}</div>
            <img src={RightIcon} alt="right-icon" className={style.rightIcon} />
          </div>
        ))}
      </div>
    </div>
  );
}
