import React, { useState, useEffect } from 'react';
import { useAuth } from './hooks.tsx';
import { useNavigate } from 'react-router';
import { Role, ClassStatus } from './components/Classroom/useClassroom.ts';
// import { TeacherView } from './components/Classroom/TeacherView.tsx';
// import { StudentView } from './components/Classroom/StudentView.tsx';
import { ClassroomLayout } from './components/Classroom/ClassroomLayout.tsx';
import { AuthLayout } from './components/Classroom/AuthLayout.tsx';
import { ClassroomProvider, useClassroomContext } from "./components/Classroom/ClassroomProvider.tsx";
import { ToastContainer } from 'react-toastify';

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
          type="button"
          onClick={() => chooseRole(Role.Teacher)}
          className="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
        >
          我是老师
        </button>
        <button
          type="button"
          onClick={() => chooseRole(Role.Student)}
          className="px-6 py-3 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
        >
          我是学生
        </button>
      </div>
    </div>
  );
};

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

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

  return (
    <div className="bg-white p-4 rounded shadow mb-4">
      <h3 className="font-bold mb-2">加入课堂</h3>
      <div className="flex space-x-2">
        <input
          type="text"
          value={classId}
          onChange={(e) => setClassId(e.target.value)}
          placeholder="输入课堂ID"
          className="flex-1 px-3 py-2 border rounded"
        />
        <button
          type="button"
          onClick={handleJoinClass}
          className="px-4 py-2 bg-blue-500 text-white rounded"
        >
          加入课堂
        </button>
      </div>
    </div>
  );
};

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

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

  return (
    <div className="bg-white p-4 rounded shadow mb-4">
      <h3 className="font-bold mb-2">创建新课堂</h3>
      <div className="flex space-x-2">
        <input
          type="text"
          value={className}
          onChange={(e) => setClassName(e.target.value)}
          placeholder="输入课堂名称"
          className="flex-1 px-3 py-2 border rounded"
        />
        <button
          type="button"
          onClick={handleCreateClass}
          className="px-4 py-2 bg-green-500 text-white rounded"
        >
          创建课堂
        </button>
      </div>
    </div>
  );
};


const Classroom = () => {
  const context = useClassroomContext();
  const { role, classStatus, isLoggedIn, login, classId, joinClass } = context;

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

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

  if (!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>
      </>
    );
  }

  if (classStatus === ClassStatus.ENDED) {
    return (
      <div className="text-center py-8">
        <h2 className="text-xl font-bold">课堂已结束</h2>
        <p>感谢参与本次课堂</p>
      </div>
    );
  }

  return (
    <ClassroomLayout role={role}>
      {/* {role === Role.Teacher ? <TeacherView /> : <StudentView />} */}
      <></>
    </ClassroomLayout>
  );
};

export const ClassroomPage = () => {
  const { user } = useAuth();
  return (
    <>
      <ClassroomProvider user={user!}>
        <Classroom />
      </ClassroomProvider>
      <ToastContainer
        position="top-right"
        autoClose={500}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
      />
    </>
  )
}