import React, { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import { getCurrentUser, refreshUserToken } from '../store/slices/authThunks';
import { setTokens } from '../store/slices/authSlice';

const AuthInitializer: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const dispatch = useAppDispatch();
  const { isAuthenticated, user } = useAppSelector((state) => state.auth);

  useEffect(() => {
    const initializeAuth = async () => {
      try {
        // Check for existing tokens in localStorage
        const accessToken = localStorage.getItem('accessToken');
        const refreshToken = localStorage.getItem('refreshToken');
        const sessionId = localStorage.getItem('sessionId');

        if (accessToken && refreshToken && sessionId) {
          // Set tokens in store
          dispatch(setTokens({
            token: accessToken,
            refreshToken,
            sessionId,
          }));

          // Try to get current user
          try {
            await dispatch(getCurrentUser()).unwrap();
          } catch (error) {
            // If getting user fails, try to refresh token
            console.log('Failed to get current user, trying to refresh token...');
            try {
              await dispatch(refreshUserToken()).unwrap();
              // Try to get user again after token refresh
              await dispatch(getCurrentUser()).unwrap();
            } catch (refreshError) {
              console.log('Token refresh failed, clearing auth data...');
              // Clear invalid tokens
              localStorage.removeItem('accessToken');
              localStorage.removeItem('refreshToken');
              localStorage.removeItem('sessionId');
            }
          }
        }
      } catch (error) {
        console.error('Auth initialization error:', error);
      }
    };

    initializeAuth();
  }, [dispatch]);

  return <>{children}</>;
};

export default AuthInitializer; 