/**
 * Copyright 2025 Beijing Volcano Engine Technology Co., Ltd. All Rights Reserved.
 * SPDX-license-identifier: BSD-3-Clause
 */

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '@/store';
import RtcClient from '@/lib/RtcClient';
import { setInterruptMsg } from '@/store/slices/room';
import { useDeviceState, useLeave } from '@/lib/useCommon';
import { COMMAND } from '@/utils/handler';
import style from './index.module.less';
import LockMicroIcon from '@/assets/img/lockmicrophone.png';
import MicroIcon from '@/assets/img/microphone.png';
import HandleOffIcon from "@/assets/img/handoff.png"

const THRESHOLD_VOLUME = 18;

function AudioController(props: React.HTMLAttributes<HTMLDivElement>) {
  const { className, ...rest } = props;
  const dispatch = useDispatch();
  const room = useSelector((state: RootState) => state.room);
  const volume = room.localUser.audioPropertiesInfo?.linearVolume || 0;
  const { isAudioPublished,switchMic } = useDeviceState();

  const { isAITalking} = useSelector((state: RootState) => state.room);
  const isLoading = volume >= THRESHOLD_VOLUME && isAudioPublished;
  const leaveRoom = useLeave();

  const handleInterrupt = () => {
    RtcClient.commandAudioBot(COMMAND.INTERRUPT);
    dispatch(setInterruptMsg());
  };

  return (
    <div className={`${className}`} {...rest}>
      <div className={`${style.microphoneWrapper}`} onClick={leaveRoom}>
        <img src={HandleOffIcon} alt="handoff" />
        <div>挂断</div>
      </div>
      <div className={`${style.microphoneWrapper}`} onClick={() => switchMic(true)}>
        <img src={isAudioPublished ? MicroIcon : LockMicroIcon} alt="lock" />
        <div>{isAudioPublished ? '关麦' : '开麦'}</div>
      </div>

      <div className={`${style.talkWrapper}`} onClick={isAITalking ? handleInterrupt : undefined}>
        <div className={`${isAITalking && isLoading ? style.isTalking : ''} ${style.listenerDot}`}>
          <span style={{ '--d': '2' } as React.CSSProperties} />
          <span style={{ '--d': '1' } as React.CSSProperties} />
          <span style={{ '--d': '0' } as React.CSSProperties} />
          <span style={{ '--d': '1' } as React.CSSProperties} />
          <span style={{ '--d': '2' } as React.CSSProperties} />
        </div>
        <div>{isAITalking ? '点击打断' : '正在听'}</div>
      </div>
    </div>
  );
}

export default AudioController;
