import React, { useState, useEffect } from 'react';
import { useAuth } from '@/client/mobile/hooks/AuthProvider';
import { useNavigate, useSearchParams } from 'react-router';
import { Role, ClassStatus } from '@/client/mobile/components/Classroom/useClassroom';
import { ClassroomLayout } from '@/client/mobile/components/Classroom/ClassroomLayout';
import { AuthLayout } from '@/client/mobile/components/Classroom/AuthLayout';
import { ClassroomProvider, useClassroomContext } from "@/client/mobile/components/Classroom/ClassroomProvider";
import { Button } from '@/client/components/ui/button';
import { Input } from '@/client/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/client/components/ui/card';

const RoleSelection = () => {
  const { setRole, login } = useClassroomContext();
  const chooseRole = (role: Role) => {

    setRole(role);
    login(role);
  }
  
  return (
    <div className="flex flex-col items-center justify-center h-full">
      <h2 className="text-2xl font-bold mb-8">请选择您的角色</h2>
      <div className="flex space-x-4">
        <Button
          onClick={() => chooseRole(Role.Teacher)}
          className="px-6 py-3"
        >
          我是老师
        </Button>
        <Button
          onClick={() => chooseRole(Role.Student)}
          variant="secondary"
          className="px-6 py-3"
        >
          我是学生
        </Button>
      </div>
    </div>
  );
};

const JoinClassSection = () => {
  const { joinClass } = useClassroomContext();
  const [classId, setClassId] = useState('');

  const handleJoinClass = async () => {
    if (!classId.trim()) return;
    await joinClass(classId);
  };

  return (
    <Card className="mb-4">
      <CardHeader>
        <CardTitle className="text-lg">加入课堂</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="flex space-x-2">
          <Input
            type="text"
            value={classId}
            onChange={(e) => setClassId(e.target.value)}
            placeholder="输入课堂ID"
            className="flex-1"
          />
          <Button
            onClick={handleJoinClass}
          >
            加入课堂
          </Button>
        </div>
      </CardContent>
    </Card>
  );
};

const CreateClassSection = () => {
  const { classStatus, createClass, className, setClassName, role } = useClassroomContext();
  const [isPrivate, setIsPrivate] = useState(false);
  const navigate = useNavigate();
  
  const handleCreateClass = async () => {
    if (!className.trim()) return;
    const classId = await createClass(className, 200, isPrivate);
    if (classId) {
      navigate(`/mobile/classroom/${classId}/${role === Role.Teacher ? Role.Teacher : Role.Student}`, { replace: true });
    }
  };

  if (classStatus !== ClassStatus.NOT_STARTED) return null;

  return (
    <Card className="mb-4">
      <CardHeader>
        <CardTitle className="text-lg">创建新课堂</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          <div className="flex space-x-2">
            <Input
              type="text"
              value={className}
              onChange={(e) => setClassName(e.target.value)}
              placeholder="输入课堂名称"
              className="flex-1"
            />
            <Button
              onClick={handleCreateClass}
              variant="secondary"
            >
              创建课堂
            </Button>
          </div>
          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="private-class"
              checked={isPrivate}
              onChange={(e) => setIsPrivate(e.target.checked)}
              className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 focus:ring-2"
            />
            <label htmlFor="private-class" className="text-sm text-gray-600">
              闭门会议（仅限学员进入）
            </label>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};


const Classroom = () => {
  const context = useClassroomContext();
  const { role, classStatus, isLoggedIn, login, classId, joinClass, setRole } = context;
  const [searchParams] = useSearchParams();

  console.log('classStatus', classStatus)
  console.log('classId', classId)
  console.log('role', role)

  // useEffect(() => {
  //   // 处理URL中的role参数
  //   const urlRole = searchParams.get('role');
  //   if (!role) {
  //     const roleValue = urlRole === Role.Teacher ? Role.Teacher : Role.Student;
  //     setRole(roleValue);
  //     login(roleValue);
  //   }
  // }, [searchParams]);

  useEffect(() => {
    
    if (!isLoggedIn && role) {
      (async () => {
        await login(role);
        if(classId)
          await joinClass(classId);
      })()
    }
  }, [isLoggedIn, role , classId]);

  if (classId && classStatus === ClassStatus.ENDED) {
    return (
      <Card className="text-center py-8">
        <CardHeader>
          <CardTitle className="text-xl">课堂已结束</CardTitle>
        </CardHeader>
        <CardContent>
          <p>感谢参与本次课堂</p>
        </CardContent>
      </Card>
    );
  }

  if (classId && classStatus === ClassStatus.PRIVATE_ACCESS_DENIED) {
    return (
      <Card className="text-center py-8">
        <CardHeader>
          <CardTitle className="text-xl">无法进入课堂</CardTitle>
        </CardHeader>
        <CardContent>
          <p>该课堂为闭门会议，只有老师和学员身份可以进入</p>
        </CardContent>
      </Card>
    );
  }

  // if (!role) {
  //   return (
  //     <AuthLayout>
  //       <RoleSelection />
  //     </AuthLayout>
  //   );
  // }

  if (classId && !isLoggedIn) {
    return (
      <AuthLayout>
        <div className="flex items-center justify-center h-full">
          <p>正在自动登录中...</p>
        </div>
      </AuthLayout>
    );
  }

  if (role === Role.Teacher && !context.isJoinedClass && !classId) {
    return (
      <>
        <AuthLayout>
          <CreateClassSection />
        </AuthLayout>
      </>
    );
  }

  if (role === Role.Student && !context.isJoinedClass && !classId) {
    return (
      <>
        <AuthLayout>
          <JoinClassSection />
        </AuthLayout>
      </>
    );
  }

  return (
    <ClassroomLayout role={role}>
      <></>
    </ClassroomLayout>
  );
};

export const ClassroomPage = () => {
  const { user } = useAuth();
  return (
    <ClassroomProvider user={user!}>
      <Classroom />
    </ClassroomProvider>
  )
}