import { Dispatch } from 'redux';

import { navigationUpdateLocation } from 'mweb/common/actions/navigation';
import { Location } from 'mweb/common/reducers/app';
import { RootState } from 'mweb/common/reducers/root';
import { channelsDataFetchChannel } from 'mweb/common/actions/data/channels';
import { ChannelProfileContentCounts } from 'mweb/common/selectors/pages/channelProfile';

export const CHANNEL_PROFILE_PAGE_CHANNEL_UPDATED_ACTION_TYPE =
  'CHANNEL_PROFILE_PAGE_CHANNEL_UPDATED_ACTION_TYPE';
export interface ChannelProfilePageChannelUpdatedAction {
  type: typeof CHANNEL_PROFILE_PAGE_CHANNEL_UPDATED_ACTION_TYPE;
  payload: {
    channel: string;
  };
}

export const CHANNEL_PROFILE_PAGE_REDIRECTED_AS_OFFLINE =
  'CHANNEL_PROFILE_PAGE_REDIRECTED_AS_OFFLINE';

export interface ChannelProfilePageRedirectAsOffline {
  type: typeof CHANNEL_PROFILE_PAGE_REDIRECTED_AS_OFFLINE;
  payload: {};
}

export function channelProfilePageTransition(
  channel: string,
  videoCounts: ChannelProfileContentCounts,
): (dispatch: Dispatch<RootState>) => Promise<void> {
  return async dispatch => {
    dispatch(channelProfilePageUpdateChannel(channel));
    await dispatch(
      channelsDataFetchChannel(channel, {
        archiveCount: videoCounts.archives,
        recentClipCount: videoCounts.recentClips,
        recentHighlightCount: videoCounts.recentHighlights,
        topClipCount: videoCounts.topClips,
        topHighlightCount: videoCounts.topHighlights,
        recentUploadCount: videoCounts.recentPremieresAndUploads,
        recentPremiereCount: videoCounts.recentPremieresAndUploads,
      }),
    );
    dispatch(navigationUpdateLocation(Location.ChannelProfile));
  };
}
export function channelProfilePageRedirectAsOffline(
  channel: string,
  videoCounts: ChannelProfileContentCounts,
): (dispatch: Dispatch<RootState>) => Promise<void> {
  return async dispatch => {
    await dispatch(channelProfilePageTransition(channel, videoCounts));
    // This should happen second since the channelProfilePageTransition
    // will trigger a navigation update and that can reset the page state.
    dispatch({
      type: CHANNEL_PROFILE_PAGE_REDIRECTED_AS_OFFLINE,
      payload: {},
    } as ChannelProfilePageRedirectAsOffline);
  };
}

export function channelProfilePageUpdateChannel(
  channel: string,
): ChannelProfilePageChannelUpdatedAction {
  return {
    type: CHANNEL_PROFILE_PAGE_CHANNEL_UPDATED_ACTION_TYPE,
    payload: {
      channel,
    },
  };
}

export type ChannelProfileAction =
  | ChannelProfilePageChannelUpdatedAction
  | ChannelProfilePageRedirectAsOffline;
