import React, { useState, useEffect } from 'react';
import { useClassroomContext } from './ClassroomProvider';
import { Button } from '@/client/components/ui/button';
import { Role } from './useClassroom';

interface RTCToggleMuteButtonProps {
  userId: string;
  userName?: string;
}

export const RTCToggleMuteButton: React.FC<RTCToggleMuteButtonProps> = ({ userId, userName }) => {
  const { role, toggleMuteMember, checkRtcMuteStatus } = useClassroomContext();
  const [isMuted, setIsMuted] = useState(false);
  const [loading, setLoading] = useState(false);

  // 只有老师才能看到音频静音按钮
  if (role !== Role.Teacher) {
    return null;
  }

  // 组件挂载时查询RTC静音状态
  useEffect(() => {
    const fetchRtcMuteStatus = () => {
      try {
        const muted = checkRtcMuteStatus(userId);
        setIsMuted(muted);
      } catch (error) {
        console.error('查询RTC静音状态失败:', error);
      }
    };
    
    fetchRtcMuteStatus();
    
    // 设置定时器定期检查状态
    const interval = setInterval(fetchRtcMuteStatus, 3000); // 每3秒检查一次
    
    return () => clearInterval(interval);
  }, [userId, checkRtcMuteStatus]);

  const handleToggleMute = async () => {
    if (loading) return;
    
    setLoading(true);
    try {
      await toggleMuteMember(userId, !isMuted);
      setIsMuted(!isMuted);
    } catch (error) {
      console.error('切换RTC静音状态失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const displayName = userName || userId;

  return (
    <Button
      onClick={handleToggleMute}
      variant="outline"
      size="sm"
      className={`text-xs ${
        isMuted 
          ? 'bg-green-100 text-green-700 hover:bg-green-200 border-green-300' 
          : 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200 border-yellow-300'
      } transition-colors`}
      disabled={loading}
      title={isMuted ? `取消 ${displayName} 的音频静音` : `静音 ${displayName} 的音频`}
    >
      {loading ? '处理中...' : (isMuted ? '取消音频' : '音频静音')}
    </Button>
  );
};