import { useNavigate, useSearchParams } from 'react-router-dom';

import { useEmbedding } from '../components/embed-provider';

import { authenticationSession } from './authentication-session';

export const useNewWindow = () => {
  const { embedState } = useEmbedding();
  const navigate = useNavigate();
  if (embedState.isEmbedded) {
    // In embedded mode, navigate within the iframe (don't open new tabs)
    return (route: string, searchParams?: string) =>
      navigate({
        pathname: route,
        search: searchParams,
      });
  } else {
    return (route: string, searchParams?: string) =>
      window.open(
        `${route}${searchParams ? '?' + searchParams : ''}`,
        '_blank',
        'noopener noreferrer',
      );
  }
};

/**
 * Opens a route in a new browser tab with automatic authentication.
 * For embedded contexts where sessionStorage isn't shared across tabs,
 * this passes the JWT token via URL for auto-login.
 */
export const useOpenInNewTab = () => {
  const { embedState } = useEmbedding();

  return (route: string, searchParams?: string) => {
    const token = authenticationSession.getToken();

    if (embedState.isEmbedded && token) {
      // In embedded mode, pass token for auto-authentication in new tab
      const encodedRedirect = encodeURIComponent(
        `${route}${searchParams ? '?' + searchParams : ''}`,
      );
      const authUrl = `/authenticate?token=${encodeURIComponent(token)}&redirect=${encodedRedirect}`;
      window.open(authUrl, '_blank', 'noopener');
    } else {
      // Non-embedded mode - token is already in localStorage
      window.open(
        `${route}${searchParams ? '?' + searchParams : ''}`,
        '_blank',
        'noopener noreferrer',
      );
    }
  };
};

export const FROM_QUERY_PARAM = 'from';
/**State param is for oauth2 flow, it is used to redirect to the page after login*/
export const STATE_QUERY_PARAM = 'state';
export const LOGIN_QUERY_PARAM = 'activepiecesLogin';
export const PROVIDER_NAME_QUERY_PARAM = 'providerName';

export const useDefaultRedirectPath = () => {
  return '/flows';
};

export const useRedirectAfterLogin = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const defaultRedirectPath = useDefaultRedirectPath();
  const from = searchParams.get(FROM_QUERY_PARAM) ?? defaultRedirectPath;
  return () => navigate(from);
};
