/**
 * Copyright 2025 Beijing Volcano Engine Technology Co., Ltd. All Rights Reserved.
 * SPDX-license-identifier: BSD-3-Clause
 */
import { useEffect, useMemo, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useSearchParams } from 'react-router-dom';

import InvokeButton from '@/pages/MainPage/MainArea/Antechamber/InvokeButton';
import HeaderGroup from '@/pages/MainPage/MainArea/Antechamber/HeaderGroup';
import MyInput from '@/pages/MainPage/MainArea/Antechamber/MyInput';

import { useJoin } from '@/lib/useCommon';
import style from './index.module.less';
import { updateAIConfig } from '@/store/slices/room';
import { requestPostMethod } from '@/app/base';

function getRandomLetters(num:number) {
  const letters = 'abcdefghijklmnopqrstuvwxyz';
  let result = '';

  // 确保请求的字母数量不超过 26
  num = Math.min(num, 26);

  // 从字母表中随机选取字母
  for (let i = 0; i < num; i++) {
    const randomIndex = Math.floor(Math.random() * letters.length);
    result += letters[randomIndex];
  }

  return result;
}



function Antechamber() {
  const dispatch = useDispatch()
  const [joining, dispatchJoin] = useJoin();
  const [isDisable,setDisable] = useState(true)
  const [searchParams] = useSearchParams();
  const userId = searchParams.get('userId') || '0'
  const username = userId;
  const pre = useMemo(() => getRandomLetters(5), []);
  const roomId = `${pre}${userId}`;


  const getToken = async () => {
    const queryData = await requestPostMethod(`/api/token`)({roomId,userId:username})
    const res = await queryData?.json();
    if(res.code === 200){
      dispatch(updateAIConfig({user_token:res.data.token}))
      setDisable(false)
    }
    
  }

  useEffect(() => {
    getToken()
  },[])
  

  const handleJoinRoom = async() => {
    if (!isDisable &&!joining) {
      await dispatchJoin(
        {
          username,
          roomId,
          publishAudio: true,
        },
        false
      );
    }
  };

  return (
    <div className={style.wrapper}>
      <HeaderGroup toRoom={handleJoinRoom} />
      <MyInput toRoom={handleJoinRoom} />
      <InvokeButton onClick={handleJoinRoom} disable={isDisable} loading={joining} className={style['invoke-btn']} />
    </div>
  );
}

export default Antechamber;
