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

type ClassroomContextType = ReturnType<typeof useClassroom>;

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

export const ClassroomProvider: React.FC<{children: React.ReactNode, user: User}> = ({ children, user }) => {
  const classroom = useClassroom({ user });

  const { id: classId, role: pathRole } = useParams();

  useEffect(() => {
    if (classId) {
      classroom.setClassId(classId);
    }
    
    if (pathRole && (pathRole === Role.Teacher || pathRole === Role.Student)) {
      classroom.setRole(pathRole === Role.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;
};