import config from '../config';
import { basicAuthConfig } from '../auth0-config';
import ReactDOM from 'react-dom';
import React from 'react';
import LoginModal from '../components/LoginModal';

// Helper function to normalize API URL
function getApiUrl() {
  const apiUrl = config.api?.url || '';
  
  // If the API URL is already a full URL (starts with http), use it as is
  if (apiUrl && (apiUrl.startsWith('http://') || apiUrl.startsWith('https://'))) {
    return apiUrl;
  }
  
  // Otherwise, use relative paths
  return '';
}

// Default mock user for offline/fallback development
const DEFAULT_USER = {
  sub: 'test-user',
  email: 'test@example.com',
  name: 'Test User',
  'https://container-mom.com/roles': ['admin']
};

// Function to show a secure login modal instead of the insecure prompt
const showSecureLoginModal = () => {
  return new Promise((resolve) => {
    // Create a container for the modal
    const modalContainer = document.createElement('div');
    modalContainer.id = 'login-modal-container';
    document.body.appendChild(modalContainer);

    // Function to remove the modal
    const removeModal = () => {
      ReactDOM.unmountComponentAtNode(modalContainer);
      document.body.removeChild(modalContainer);
    };

    // Render the login modal
    ReactDOM.render(
      <LoginModal 
        onLogin={(password) => {
          removeModal();
          resolve(password);
        }}
        onCancel={() => {
          removeModal();
          resolve(null);
        }}
      />,
      modalContainer
    );
  });
};

export const authService = {
  login: async () => {
    try {
      // For basic auth, show the secure login modal
      if (basicAuthConfig.enabled) {
        const password = await showSecureLoginModal();
        if (password) {
          window.sessionStorage.setItem('test_auth_pwd', password);
          // Redirect to homepage after setting password
          window.location.href = '/';
          return;
        }
      }
      
      // Use relative path if API URL is not set
      window.location.href = '/api/auth/login';
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  },

  logout: async () => {
    try {
      // For basic auth, clear the stored password
      if (basicAuthConfig.enabled) {
        window.sessionStorage.removeItem('test_auth_pwd');
        window.location.href = '/';
        return;
      }
      
      // Use relative path if API URL is not set
      window.location.href = '/api/auth/logout';
    } catch (error) {
      console.error('Logout error:', error);
      throw error;
    }
  },

  getUser: async () => {
    try {
      // For basic auth with no stored password, return null
      if (basicAuthConfig.enabled && !window.sessionStorage.getItem('test_auth_pwd')) {
        return null;
      }
      
      // Set up headers for the request
      const headers = {
        'Accept': 'application/json'
      };

      // Add Basic Auth header if enabled
      if (basicAuthConfig.enabled) {
        const credentials = btoa(`${basicAuthConfig.username}:${window.sessionStorage.getItem('test_auth_pwd') || ''}`);
        headers['Authorization'] = `Basic ${credentials}`;
      }

      try {
        const response = await fetch(`/api/auth/user`, {
          credentials: 'include',
          headers
        });

        // Log response details for debugging
        console.debug('Auth response status:', response.status);

        if (response.status === 401 && basicAuthConfig.enabled) {
          // If we get a 401 with basic auth, show the secure login modal
          const password = await showSecureLoginModal();
          if (password) {
            // Store temporarily in session storage (will be cleared on page reload/browser close)
            window.sessionStorage.setItem('test_auth_pwd', password);
            // Retry with the password
            return authService.getUser();
          } else {
            return null;
          }
        }

        if (!response.ok) {
          throw new Error(`Failed to get user: ${response.status}`);
        }

        const text = await response.text();
        
        // If the response is empty or whitespace, return null
        if (!text || !text.trim()) {
          console.log('Empty response from server, falling back to default user');
          return basicAuthConfig.enabled && window.sessionStorage.getItem('test_auth_pwd') 
            ? DEFAULT_USER 
            : null;
        }
        
        console.debug('Auth response text:', text);

        try {
          return JSON.parse(text);
        } catch (e) {
          console.error('JSON parse error:', e);
          // Return default user when basic auth is enabled as a fallback
          if (basicAuthConfig.enabled && window.sessionStorage.getItem('test_auth_pwd')) {
            console.log('Using default user due to JSON parse error');
            return DEFAULT_USER;
          }
          return null;
        }
      } catch (networkError) {
        console.error('Network error:', networkError);
        // For basic auth, provide a fallback user when backend is unavailable
        if (basicAuthConfig.enabled && window.sessionStorage.getItem('test_auth_pwd')) {
          console.log('Network error occurred, using default user');
          return DEFAULT_USER;
        }
        return null;
      }
    } catch (error) {
      console.error('Get user error:', error);
      // Default fallback for any errors
      if (basicAuthConfig.enabled && window.sessionStorage.getItem('test_auth_pwd')) {
        return DEFAULT_USER;
      }
      return null;
    }
  }
};

export const isAuthEnabled = () => {
  return basicAuthConfig.enabled;
};
