'use client';
import React, { createContext, useContext, useState, useEffect } from 'react';
import { flushSync } from 'react-dom';
import logger from '@/utils/logger';

const EstablishmentContext = createContext();

export const EstablishmentProvider = ({ children }) => {
  const [selectedEstablishmentId, setSelectedEstablishmentIdState] = useState(
    () => {
      const storedEstablishmentId = +sessionStorage.getItem(
        'selectedEstablishmentId'
      );
      return storedEstablishmentId;
    }
  );
  const [
    selectedEstablishmentEvaluationFrequency,
    setSelectedEstablishmentEvaluationFrequencyState,
  ] = useState(() => {
    const storedEstablishmentEvaluationFrequency = +sessionStorage.getItem(
      'selectedEstablishmentEvaluationFrequency'
    );
    return storedEstablishmentEvaluationFrequency;
  });
  const [
    selectedEstablishmentTotalCapacity,
    setSelectedEstablishmentTotalCapacityState,
  ] = useState(() => {
    const storedEstablishmentTotalCapacity = +sessionStorage.getItem(
      'selectedEstablishmentTotalCapacity'
    );
    return storedEstablishmentTotalCapacity;
  });
  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;
  });
  const [selectedEstablishmentLogo, setSelectedEstablishmentLogoState] =
    useState(() => {
      const storedLogo = sessionStorage.getItem('selectedEstablishmentLogo');
      return storedLogo ? JSON.parse(storedLogo) : null;
    });

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

  const setSelectedEstablishmentEvaluationFrequency = (id) => {
    setSelectedEstablishmentEvaluationFrequencyState(id);
    logger.debug('setSelectedEstablishmentEvaluationFrequency', id);
    sessionStorage.setItem('selectedEstablishmentEvaluationFrequency', id);
  };

  const setSelectedEstablishmentTotalCapacity = (id) => {
    setSelectedEstablishmentTotalCapacityState(id);
    logger.debug('setSelectedEstablishmentTotalCapacity', id);
    sessionStorage.setItem('selectedEstablishmentTotalCapacity', 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));
  };

  const setSelectedEstablishmentLogo = (logo) => {
    setSelectedEstablishmentLogoState(logo);
    sessionStorage.setItem('selectedEstablishmentLogo', JSON.stringify(logo));
  };

  /**
   * 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);
    const userEstablishments = user.roles.map((role, i) => ({
      id: role.establishment__id,
      name: role.establishment__name,
      evaluation_frequency: role.establishment__evaluation_frequency,
      total_capacity: role.establishment__total_capacity,
      logo: role.establishment__logo,
      role_id: i,
      role_type: role.role_type,
    }));
    let roleIndexDefault = 0;
    if (user.roles && user.roles.length > 0) {
      if (userEstablishments.length > user.roleIndexLoginDefault) {
        roleIndexDefault = user.roleIndexLoginDefault;
      }
    }
    // flushSync force React à commiter tous les setState de manière synchrone
    // avant que endInitFunctionHandler (router.push) soit appelé.
    // Sans ça, ProtectedRoute verrait user=null au premier rendu post-navigation.
    flushSync(() => {
      setUser(user);
      setEstablishments(userEstablishments);
      if (user.roles && user.roles.length > 0) {
        setSelectedRoleId(roleIndexDefault);
        if (userEstablishments.length > 0) {
          setSelectedEstablishmentId(userEstablishments[roleIndexDefault].id);
          setSelectedEstablishmentEvaluationFrequency(
            userEstablishments[roleIndexDefault].evaluation_frequency
          );
          setSelectedEstablishmentTotalCapacity(
            userEstablishments[roleIndexDefault].total_capacity
          );
          setSelectedEstablishmentLogo(
            userEstablishments[roleIndexDefault].logo
          );
          setProfileRole(userEstablishments[roleIndexDefault].role_type);
        }
      }
    });
    logger.debug('Establishments', user.roleIndexLoginDefault);
    if (user.roles && user.roles.length > 0) {
      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);
    setSelectedEstablishmentEvaluationFrequencyState(null);
    setSelectedEstablishmentTotalCapacityState(null);
    setSelectedEstablishmentLogoState(null);
    sessionStorage.clear();
  };

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

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