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

import React, { useRef, useEffect, useState } from 'react';
import { useSelector,useDispatch } from 'react-redux';
import { Tag, Spin } from '@arco-design/web-react';
import { RootState } from '@/store';
import Loading from '@/components/Loading/HorizonLoading';
import Config from '@/config';
import styles from './index.module.less';
import { COMMAND, INTERRUPT_PRIORITY } from '@/utils/handler';
import RtcClient from '@/lib/RtcClient';
import { setCurrentMsg, setHistoryMsg } from '@/store/slices/room';

interface Message {
  value: string;
  user: string;
  isInterrupted?: boolean;
}

const lines: (string | React.ReactNode)[] = [];

function Conversation(props: React.HTMLAttributes<HTMLDivElement>) {
  const { className, ...rest } = props;
  const msgHistory = useSelector((state: RootState) => state.room.msgHistory);
  const { userId } = useSelector((state: RootState) => state.room.localUser);
  const { isAITalking, isUserTalking, initMsg} = useSelector((state: RootState) => state.room);
  const isAIReady = msgHistory.length > 0;
  const containerRef = useRef<HTMLDivElement>(null);
  const [isFirst,setIsFirst] = useState(true);
  const [isAudioBotEnabled, setIsAudioBotEnabled] = useState(false);
  
  const dispatch = useDispatch()

  useEffect(() => {
    const checkAudioBotStatus = () => {
      setIsAudioBotEnabled(RtcClient.getAudioBotEnabled());
    };
    
    // 初始检查
    checkAudioBotStatus();
    
    // 设置定时器定期检查
    const timer = setInterval(checkAudioBotStatus, 1000);
    
    // 清理函数
    return () => clearInterval(timer);
  }, []);

  useEffect(() => {        
    const container = containerRef.current;
    if (container) {
      container.scrollTop = container.scrollHeight - container.clientHeight;
    }
  }, [msgHistory.length]);

  useEffect(() => {
    if(isFirst && initMsg && isAudioBotEnabled){
      RtcClient.commandAudioBot(COMMAND.EXTERNAL_TEXT_TO_LLM, INTERRUPT_PRIORITY.HIGH, initMsg);
      dispatch(
        setHistoryMsg({
          text: initMsg,
          user: RtcClient.basicInfo.user_id,
          paragraph: true,
          definite: true,
        })
      );
      dispatch(
        setCurrentMsg({
          text: initMsg,
          user: RtcClient.basicInfo.user_id,
          paragraph: true,
          definite: true,
        }))
      setIsFirst(false)
    }
  },[isAudioBotEnabled])

  return (
    <div ref={containerRef} className={`${styles.conversation} ${className}`} {...rest}>
      {lines.map((line) => line)}
      {!isAIReady ? (
        <div className={styles.aiReadying}>
          <Spin size={16} className={styles['aiReading-spin']} />
          AI 准备中, 请稍侯
        </div>
      ) : (
        ''
      )}
      {msgHistory?.map(({ value, user, isInterrupted }: Message, index: number) => {
        const isUserMsg = user === userId;
        const isRobotMsg = user === Config.BotName;
        if (!isUserMsg && !isRobotMsg) {
          return '';
        }
        return (
          <div
            className={`${styles.sentence} ${isUserMsg ? styles.user : styles.robot}`}
            key={`msg-${index}`}
          >
            <div className={styles.content}>
              {value}
              <div className={styles['loading-wrapper']}>
                {isAIReady && (isUserTalking || isAITalking) && index === msgHistory.length - 1 ? (
                  <Loading gap={1} className={styles.loading} dotClassName={styles.dot} />
                ) : (
                  ''
                )}
              </div>
            </div>
            {!isUserMsg && isInterrupted ? <Tag className={styles.interruptTag}>已打断</Tag> : ''}
          </div>
        );
      })}
    </div>
  );
}

export default Conversation;
