import { Dispatch } from 'redux';

import { RootState } from 'mweb/common/reducers/root';
import { Location } from 'mweb/common/reducers/app';
import { navigationUpdateLocation } from 'mweb/common/actions/navigation';
import { trackingTrackPageView } from 'mweb/common/actions/tracking';
import { channelsDataFetchChannel } from 'mweb/common/actions/data/channels';

export const CHAT_EMBED_PAGE_CHANNEL_UPDATED_ACTION_TYPE =
  'CHAT_EMBED_PAGE_CHANNEL_UPDATED_ACTION_TYPE';
export interface ChatEmbedPageChannelUpdatedAction {
  type: typeof CHAT_EMBED_PAGE_CHANNEL_UPDATED_ACTION_TYPE;
  payload: {
    channel: string;
  };
}

export type ChatEmbedPageAction = ChatEmbedPageChannelUpdatedAction;

export function chatEmbedPageTransition(
  channel: string,
): (dispatch: Dispatch<RootState>) => Promise<void> {
  return async dispatch => {
    dispatch(chatEmbedPageUpdateChannel(channel));
    await dispatch(channelsDataFetchChannel(channel));
    dispatch(navigationUpdateLocation(Location.ChatEmbed));
  };
}

export function chatEmbedPageTransitionClient(): (
  dispatch: Dispatch<RootState>,
) => void {
  return dispatch => {
    dispatch(trackingTrackPageView(Location.ChatEmbed));
  };
}

export function chatEmbedPageUpdateChannel(
  channel: string,
): ChatEmbedPageChannelUpdatedAction {
  return {
    type: CHAT_EMBED_PAGE_CHANNEL_UPDATED_ACTION_TYPE,
    payload: {
      channel,
    },
  };
}
