import {JSX, useEffect, useRef} from 'react';
import Routes from '../../routers/static-routes';
import {useAppSelector} from '../../hooks/store';
import {selectIsAuthenticated, selectIsAuthenticating} from '../../store/slices/Authentication.slice';

interface AuthorizedOnlyProps {
  children: JSX.Element;
  fallback?: JSX.Element;
  redirectTo?: string;
}

export function AuthorizedOnly({children, fallback, redirectTo = Routes.loginUrl()}: AuthorizedOnlyProps): JSX.Element {
  const isAuthenticated = useAppSelector(selectIsAuthenticated);
  const isAuthenticating = useAppSelector(selectIsAuthenticating);
  const hasRedirected = useRef(false);

  useEffect(() => {
    // If not authenticating and not authenticated, redirect to login
    if (!isAuthenticating && !isAuthenticated && !hasRedirected.current) {
      hasRedirected.current = true;

      // Build the redirect URL with current query parameters
      const currentSearch = window.location.search;
      const currentUrl = window.location.href;

      console.log('AuthorizedOnly: Redirecting to login');
      console.log('Current URL:', currentUrl);
      console.log('Current search:', currentSearch);
      console.log('Redirect to:', redirectTo);

      // Ensure we have the full path for redirect
      const loginPath = redirectTo.startsWith('/') ? redirectTo : `/${redirectTo}`;
      const redirectUrl = currentSearch ? `${loginPath}${currentSearch}` : loginPath;

      window.location.href = redirectUrl;
    }
  }, [isAuthenticated, isAuthenticating, redirectTo]);

  // Reset redirect flag when authentication state changes
  useEffect(() => {
    if (isAuthenticated) {
      hasRedirected.current = false;
    }
  }, [isAuthenticated]);

  // Show fallback while checking authentication or redirecting
  if (!isAuthenticated) {
    return (
      fallback || (
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            height: '100vh',
            color: '#666'
          }}>
          <h2>Checking Authentication...</h2>
          <p>Please wait while we verify your credentials.</p>
        </div>
      )
    );
  }

  // User is authenticated, render the protected content
  return children;
}
