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

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

export const IMToggleMuteButton: React.FC<IMToggleMuteButtonProps> = ({ userId, userName }) => {
  const { role, muteStudentIM, unmuteStudentIM, classId, checkMuteStatus } = useClassroomContext();
  const [isMuted, setIsMuted] = useState(false);
  const [loading, setLoading] = useState(false);

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

  // 组件挂载时查询禁言状态
  useEffect(() => {
    const fetchMuteStatus = async () => {
      if (!classId) return;
      
      try {
        const muted = await checkMuteStatus(userId);
        setIsMuted(muted);
      } catch (error) {
        console.error('查询禁言状态失败:', error);
      }
    };
    
    fetchMuteStatus();
  }, [userId, classId, checkMuteStatus]);

  const handleToggleMute = async () => {
    if (loading) return;
    
    setLoading(true);
    try {
      if (isMuted) {
        await unmuteStudentIM(userId);
        setIsMuted(false);
      } else {
        await muteStudentIM(userId);
        setIsMuted(true);
      }
    } catch (error) {
      console.error('切换禁言状态失败:', 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-purple-100 text-purple-700 hover:bg-purple-200 border-purple-300'
      } transition-colors`}
      disabled={loading}
      title={isMuted ? `解禁 ${displayName}（IM聊天）` : `禁言 ${displayName}（IM聊天）`}
    >
      {loading ? '处理中...' : (isMuted ? '解禁IM' : 'IM禁言')}
    </Button>
  );
};