import React, { useState } from 'react';
import { useClassroomContext } from './ClassroomProvider';
import { ClassStatus } from './useClassroom';
import { StopIcon } from '@heroicons/react/24/outline';
import { Button } from '@/client/components/ui/button';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/client/components/ui/alert-dialog';

export const TeacherClassControlButton: React.FC = () => {
  const { endClass, classStatus } = useClassroomContext();
  const [isConfirmOpen, setIsConfirmOpen] = useState(false);

  const handleEndClass = async () => {
    await endClass();
    setIsConfirmOpen(false);
  };

  const openConfirmDialog = () => {
    setIsConfirmOpen(true);
  };

  return (
    <>
      <Button
        type="button"
        onClick={openConfirmDialog}
        className={`p-2 rounded-full ${classStatus === ClassStatus.ENDED ? 'bg-gray-500' : 'bg-red-500'} text-white`}
        title={classStatus === ClassStatus.ENDED ? '课堂已结束' : '结束课堂'}
        size="icon"
        variant="ghost"
      >
        <StopIcon className="w-4 h-4" />
      </Button>

      <AlertDialog open={isConfirmOpen} onOpenChange={setIsConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>结束课堂确认</AlertDialogTitle>
            <AlertDialogDescription>
              确定要结束课堂吗？所有学生将被断开连接。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={handleEndClass}>
              确定结束
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};