/**
 * Copyright 2025 Beijing Volcano Engine Technology Co., Ltd. All Rights Reserved.
 * SPDX-license-identifier: BSD-3-Clause
 */
import { useEffect, 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 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 roomId = `${userId}-${new Date().getTime()}`;


  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;
