import { useState, useEffect, useContext } from "react";

import HelloGIF from "/icons/hello.gif";
import WhatsThing from "/icons/whatsThing.png";
import CircleIcon from "/icons/circle.png";
import RightIcon from "/icons/right.png";
import styles from "./index.module.css";
import { RealtimeClientContext } from "../Provider/RealtimeClientProvider";
// import Countdown from "../Countdown";

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

  const { handleConnect } = useContext(RealtimeClientContext);


  // 随机获取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 () => {
    setAllQuestions(["济南500分还能上哪些高中？", "第二批志愿怎么填最稳", "指标生和统招生区别"]);
  };

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

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

  const handleClick = () => {
    setIsRotating(true);

    // 更新随机问题
    setDisplayQuestions(getRandomQuestions());

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

  const handleQuestion = async (question: string) => {
    handleConnect({ initMessage: question });
  };

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