import React, { useState, useEffect, useRef, createContext, useContext } from 'react';
import { useParams } from 'react-router';
import { useClassroom , Role } from './useClassroom.ts';

type ClassroomContextType = ReturnType<typeof useClassroom>;

const ClassroomContext = createContext<ClassroomContextType | null>(null);

export const ClassroomProvider: React.FC<{children: React.ReactNode}> = ({ children }) => {
  const classroom = useClassroom();
  const { id: classId, role: pathRole } = useParams();

  useEffect(() => {
    if (classId) {
      classroom.setClassId(classId);
    }
    
    if (pathRole && ['teacher', 'student'].includes(pathRole)) {
      classroom.setRole(pathRole === 'teacher' ? Role.Teacher : Role.Student);
    }
  }, [classId, pathRole]);

  return (
    <ClassroomContext.Provider value={classroom}>
      {children}
    </ClassroomContext.Provider>
  );
};

export const useClassroomContext = () => {
  const context = useContext(ClassroomContext);
  if (!context) {
    throw new Error('useClassroomContext must be used within a ClassroomProvider');
  }
  return context;
};