import React, { useState } from 'react';
import { useClassroomContext } from './ClassroomProvider';
import { UserGroupIcon, EyeIcon, UsersIcon } from '@heroicons/react/24/outline';
import { Button } from '@/client/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/client/components/ui/card';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/client/components/ui/alert-dialog';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/client/components/ui/dialog';
import { IMToggleMuteButton } from './IMToggleMuteButton';
import { RTCToggleMuteButton } from './RTCToggleMuteButton';
import { useAuth } from '../../hooks/AuthProvider';

export const TeacherStudentManagementButton: React.FC = () => {
  const { user } = useAuth();
  const { students, kickStudent, onlineCount, pvCount } = useClassroomContext();
  const [showPanel, setShowPanel] = useState(false);
  const [confirmDialog, setConfirmDialog] = useState<{
    open: boolean;
    action: 'kick' | null;
    studentId: string;
    studentName: string;
  }>({
    open: false,
    action: null,
    studentId: '',
    studentName: '',
  });

  const openConfirmDialog = (action: 'kick', studentId: string, studentName: string) => {
    setConfirmDialog({
      open: true,
      action,
      studentId,
      studentName,
    });
  };

  const handleConfirm = () => {
    const { action, studentId } = confirmDialog;
    
    switch (action) {
      case 'kick':
        kickStudent(studentId);
        break;
    }
    
    setConfirmDialog({
      open: false,
      action: null,
      studentId: '',
      studentName: '',
    });
  };

  const handleCancel = () => {
    setConfirmDialog({
      open: false,
      action: null,
      studentId: '',
      studentName: '',
    });
  };

  return (
    <Dialog open={showPanel} onOpenChange={setShowPanel}>
      <DialogTrigger asChild>
        <Button
          type="button"
          className="p-2 rounded-full bg-blue-500 text-white relative"
          title={`人员管理 (${students.length})`}
          size="icon"
          variant="ghost"
        >
          <UserGroupIcon className="w-4 h-4" />
          {students.length > 0 && (
            <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-4 h-4 flex items-center justify-center">
              {students.length}
            </span>
          )}
        </Button>
      </DialogTrigger>
      
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center">
            <UserGroupIcon className="w-4 h-4 mr-2 text-blue-500" />
            人员管理 ({students.length})
          </DialogTitle>
        </DialogHeader>
        
        <Card className="border-0 shadow-none">
          <CardContent className="p-0">
            {/* 统计信息 */}
            <div className="flex justify-between mb-3 p-2 bg-gray-50 rounded text-sm">
              <div className="flex items-center">
                <UsersIcon className="w-4 h-4 mr-1 text-blue-500" />
                <span>在线: {onlineCount}人</span>
              </div>
              <div className="flex items-center">
                <EyeIcon className="w-4 h-4 mr-1 text-green-500" />
                <span>看过: {pvCount}人</span>
              </div>
            </div>
            
            <div className="max-h-60 overflow-y-auto">
              {students.length === 0 ? (
                <p className="text-gray-500 text-sm">暂无学生加入</p>
              ) : (
                <div className="space-y-2">
                  {students.map((student) => (
                    <div key={student.id} className="flex items-center justify-between p-2 border rounded text-sm">
                      <span>{student.name}</span>
                      <div className="flex gap-1 flex-wrap">
                       {Number(student.id) !== user?.id && (
                        <>
                          <RTCToggleMuteButton userId={student.id} userName={student.name} />
                          <IMToggleMuteButton userId={student.id} userName={student.name} />
                          <Button
                            onClick={() => openConfirmDialog('kick', student.id, student.name)}
                            variant="outline"
                            size="sm"
                            className="text-xs bg-red-100 text-red-700 hover:bg-red-200 border-red-300"
                          >
                            移出
                          </Button>
                       </>
                      )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </DialogContent>

      <AlertDialog open={confirmDialog.open} onOpenChange={(open) => !open && handleCancel()}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>操作确认</AlertDialogTitle>
            <AlertDialogDescription>
              {confirmDialog.action === 'kick' && `确定要移出 ${confirmDialog.studentName} 吗？`}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={handleConfirm}>
              确定
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Dialog>
  );
};