import React, { createContext, useContext, useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import logger from '@/utils/logger';

const EstablishmentContext = createContext();

export const EstablishmentProvider = ({ children }) => {
  const { data: session, status } = useSession();
  const [selectedEstablishmentId, setSelectedEstablishmentId] = useState(null);
  const [profileRole, setProfileRole] = useState(null);
  const [establishments, setEstablishments] = useState([]);
  const [user, setUser] = useState(null);

  useEffect(() => {
    if (status === 'loading') return; // Attendre que le statut de la session soit défini

    if (session && session.user) {
      setUser(session.user);
      console.log("getSession");
      const userEstablishments = session.user.roles.map(role => ({
        id: role.establishment__id,
        name: role.establishment__name,
        role_type: role.role_type
      }));
      setEstablishments(userEstablishments);
      // Sélectionner l'établissement depuis la session ou le premier établissement par défaut
      if (userEstablishments.length > 0) {
        setSelectedEstablishmentId(userEstablishments[0].id);
        setProfileRole(userEstablishments[0].role_type);
      }
    }
  }, [session, status]);

  return (
    <EstablishmentContext.Provider value={{ selectedEstablishmentId, setSelectedEstablishmentId, profileRole, setProfileRole, establishments, user }}>
      {children}
    </EstablishmentContext.Provider>
  );
};

export const useEstablishment = () => {
  return useContext(EstablishmentContext);
};