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

const EstablishmentContext = createContext();

export const EstablishmentProvider = ({ children }) => {
  const [selectedEstablishmentId, setSelectedEstablishmentIdState] = useState(
    () => {
      const storedEstablishmentId = +sessionStorage.getItem(
        'selectedEstablishmentId'
      );
      return storedEstablishmentId;
    }
  );
  const [selectedRoleId, setSelectedRoleIdState] = useState(() => {
    const storedRoleId = +sessionStorage.getItem('selectedRoleId');
    return storedRoleId;
  });
  const [profileRole, setProfileRoleState] = useState(() => {
    const storedProfileRole = +sessionStorage.getItem('profileRole');
    return storedProfileRole;
  });
  const [establishments, setEstablishmentsState] = useState(() => {
    const storedEstablishments = sessionStorage.getItem('establishments');
    return storedEstablishments ? JSON.parse(storedEstablishments) : [];
  });
  const [user, setUserState] = useState(() => {
    const storedUser = sessionStorage.getItem('user');
    return storedUser ? JSON.parse(storedUser) : null;
  });

  // Sauvegarder dans sessionStorage à chaque mise à jour
  const setSelectedEstablishmentId = (id) => {
    setSelectedEstablishmentIdState(id);
    logger.debug('setSelectedEstablishmentId', id);
    sessionStorage.setItem('selectedEstablishmentId', id);
  };

  const setSelectedRoleId = (id) => {
    setSelectedRoleIdState(id);
    sessionStorage.setItem('selectedRoleId', id);
  };

  const setProfileRole = (role) => {
    setProfileRoleState(role);
    sessionStorage.setItem('profileRole', role);
  };

  const setEstablishments = (establishments) => {
    setEstablishmentsState(establishments);
    sessionStorage.setItem('establishments', JSON.stringify(establishments));
  };

  const setUser = (user) => {
    setUserState(user);
    sessionStorage.setItem('user', JSON.stringify(user));
  };

  /**
   * Fonction d'initialisation du contexte avec la session (appelée lors du login)
   * @param {*} session
   * @param {*} endInitFunctionHandler
   */
  const initializeContextWithSession = (session, endInitFunctionHandler) => {
    if (!session || !session.user) {
      throw new Error('Session not found');
    }
    const user = session.user;
    logger.debug('User Session:', user);
    setUser(user);
    logger.debug('Establishments User= ', user);
    const userEstablishments = user.roles.map((role, i) => ({
      id: role.establishment__id,
      name: role.establishment__name,
      role_id: i,
      role_type: role.role_type,
    }));
    setEstablishments(userEstablishments);
    logger.debug('Establishments', user.roleIndexLoginDefault);
    if (user.roles && user.roles.length > 0) {
      let roleIndexDefault = 0;
      if (userEstablishments.length > user.roleIndexLoginDefault) {
        roleIndexDefault = user.roleIndexLoginDefault;
      }
      setSelectedRoleId(roleIndexDefault);
      if (userEstablishments.length > 0) {
        setSelectedEstablishmentId(userEstablishments[roleIndexDefault].id);
        setProfileRole(userEstablishments[roleIndexDefault].role_type);
      }
      if (endInitFunctionHandler) {
        const role = session.user.roles[roleIndexDefault].role_type;
        endInitFunctionHandler(role);
      }
    } else {
      setErrorMessage('Aucun rôle trouvé pour le profil sélectionné.');
    }
  };

  const clearContext = () => {
    setSelectedEstablishmentIdState(null);
    setSelectedRoleIdState(null);
    setProfileRoleState(null);
    setEstablishmentsState([]);
    setUserState(null);
    sessionStorage.clear();
  };

  return (
    <EstablishmentContext.Provider
      value={{
        initializeContextWithSession,
        clearContext,
        selectedEstablishmentId,
        setSelectedEstablishmentId,
        selectedRoleId,
        setSelectedRoleId,
        profileRole,
        setProfileRole,
        establishments,
        setEstablishments,
        user,
        setUser,
      }}
    >
      {children}
    </EstablishmentContext.Provider>
  );
};

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