import { stringify } from 'qs';

import { IN_HOUSE_ANALYTICS_SUB_STRING } from '../../constants';

import { slice } from '../slices';

const nameSpace = slice.name;

export const accountSelector = (state$) => state$[nameSpace].account;
export const menuSelector = (state$) => state$[nameSpace].menu;
export const accountOptionsSelector = (state$) => state$[nameSpace].accountOptions;
export const storedInHouseMenuSettingsSelector = (state$) => state$[nameSpace].storedInHouseMenuSettings;
export const selectedAnalyticSelector = (state$) => state$[nameSpace].selectedAnalytic;
export const publisherNameSelector = (state$) => state$[nameSpace].publisherName;
export const salesforceIdSelector = (state$) => state$[nameSpace].salesforceId;
export const isLoadingUrlSelector = (state$) => state$[nameSpace].isLoadingUrl;
export const lookerReportUrlSelector = (state$) => state$[nameSpace].lookerReportUrl;
export const statusOverallFailureSelector = (state$) => state$[nameSpace].statusOverallFailure;
export const statusShowPopupSelector = (state$) => state$[nameSpace].statusShowPopup;
export const statusPopupMessageSelector = (state$) => state$[nameSpace].statusPopupMessage;

export const getMenuSelector = (state$) => {
  const account = accountSelector(state$);
  const menu = menuSelector(state$);
  const storedInHouseMenuSettings = storedInHouseMenuSettingsSelector(state$);

  const menuByType = menu.reduce(
    (acc, value) => ({
      ...acc,
      [value.type]: [].concat(acc[value.type] ?? [], value),
    }),
    {},
  );

  const createLookerMenuItem = (item) => {
    const queryParams = { selectedAnalytic: item.name };

    if (account) {
      queryParams.publisherName = account.label;
      queryParams.salesforceId = account.salesforceId;
    }

    return {
      title: item.name,
      href: `/analytics?${stringify(queryParams)}`,
    };
  };

  const createInHouseMenuItem = (item) => {
    const [, type] = item.lookerReportId.split('::');
    return storedInHouseMenuSettings[type] ?? null;
  };

  const createMenuByType = (menuListByType) => {
    if (!menuListByType) {
      return [];
    }

    const menuResult = menuListByType.map((menuItem) => {
      const isInHouseMenuItem = menuItem.lookerReportId.includes(IN_HOUSE_ANALYTICS_SUB_STRING);
      return isInHouseMenuItem ? createInHouseMenuItem(menuItem) : createLookerMenuItem(menuItem);
    });

    return menuResult.filter(Boolean);
  };

  return {
    generalMenu: createMenuByType(menuByType.general),
    customMenu: createMenuByType(menuByType.custom),
  };
};
