import { useEffect } from 'react';

import { isProductionEnv } from '~/lib/getSongwhipEnv';
import { OrchardBrands } from '~/lib/songwhipApi/types';
import PageLoading from '~/src/components/PageLoading';
import { useTracker } from '~/src/lib/tracker/useTracker';
import { useDispatch, useSelector } from '~/src/store/redux';
import { logoutAction } from '~/src/store/session/actions/auth';
import {
  selectSessionUserId,
  selectUserBrand,
} from '~/src/store/session/selectors';

const getLogoutDomain = (brand: OrchardBrands) => {
  if (isProductionEnv()) {
    if (brand === OrchardBrands.AWAL) return 'awal.com';
    if (brand === OrchardBrands.ORCHARD) return 'theorchard.com';

    // SME doesn't have a production logout domain yet
    // if (brand === OrchardBrands.SME) return 'sonymusic.com';
    return undefined;
  }

  if (brand === OrchardBrands.AWAL) return 'qaawal.com';
  if (brand === OrchardBrands.ORCHARD) return 'qaorch.com';

  // Even if we do have a logout domain for SME in QA, we don't redirect to it,
  // so we are consistent with production
  // if (brand === OrchardBrands.SME) return 'qapdesuite.com';
  return undefined;
};

const LogoutPage = () => {
  const userId = useSelector(selectSessionUserId);
  const brand = useSelector(selectUserBrand);

  const { trackEvent } = useTracker();
  const dispatch = useDispatch();

  useEffect(() => {
    const logout = async () => {
      // track before redux action so user is still in redux store
      // and event payload contains user-params
      if (userId) {
        await trackEvent({
          type: 'logout',
          userId,
        });
      }

      await dispatch(logoutAction());

      const domain = brand ? getLogoutDomain(brand) : undefined;

      if (domain) location.assign(`https://settings.${domain}/logout`);
      // Set the prompt query param to "login" to force the user to login again
      // If we don't set this and the auth0 session is still valid,
      // the user will be re-authenticated and redirected to the home page again.
      else location.replace(`/login?prompt=login`);
    };

    void logout();
  }, []);

  return <PageLoading />;
};

export default LogoutPage;
