// @flow

import Color from 'color';
import type { ThemeOverrides } from './theme.types';
import { whitelabelDefaults } from './whitelabel-defaults.theme';
import type { ColorPalette } from '../mixins/branding';

type ColorTable = $Shape<ColorPalette>;

/**
 * These are the magic values for darkening and lightening
 */
export const _whiteLabelShadingValues = {
  dark: 0.3,
  fg: 0.5,
  bg: 0.5,
  hover: 0.1,
};

/**
 * Generates colours with brand naming conventions for PatchworkTheme.colorPalette
 */
export const _generateBrandColors = (
  brandKeyword?: string,
  hexIn?: ?string,
): ColorTable => {
  if (brandKeyword === undefined || hexIn === undefined || hexIn === null) {
    return {};
  }

  const baseColor = new Color(hexIn);
  const hoverMixer = new Color(
    baseColor.isDark()
      ? whitelabelDefaults.colorPalette.white
      : whitelabelDefaults.colorPalette['greyscale-black'],
  );

  const baseHover = baseColor.mix(hoverMixer, _whiteLabelShadingValues.hover);
  const fg = baseColor.darken(_whiteLabelShadingValues.fg);
  const fgHover = fg.mix(hoverMixer, _whiteLabelShadingValues.hover);

  const bg = baseColor.lighten(_whiteLabelShadingValues.bg);
  const bgHover = bg.mix(hoverMixer, _whiteLabelShadingValues.hover);

  return {
    [`brand-${brandKeyword}-base`]: baseColor.hex(),
    [`brand-${brandKeyword}-base-hover`]: baseHover.hex(),
    [`brand-${brandKeyword}-fg`]: fg.hex(),
    [`brand-${brandKeyword}-fg-hover`]: fgHover.hex(),
    [`brand-${brandKeyword}-bg`]: bg.hex(),
    [`brand-${brandKeyword}-bg-hover`]: bgHover.hex(),
  };
};

export const _generateAuxColors = (color?: string): ColorTable =>
  color === undefined
    ? {}
    : {
        'aux-1': Color(color).lighten(_whiteLabelShadingValues.bg).hex(),
        'aux-2': color,
        'aux-3': Color(color).darken(_whiteLabelShadingValues.dark).hex(),
        'aux-4': Color(color).darken(_whiteLabelShadingValues.fg).hex(),
      };

/**
 * When given a base colorPalette, generates shades of primary and secondary colour overrides
 * @param {PatchworkTheme.colorPalette} colorPalette
 * @param {String} primary
 * @param {String} secondary
 */
export const _getColorPaletteOverrides = (
  colorPalette: ColorPalette,
  primary?: string,
  secondary?: string,
) => ({
  ...colorPalette,
  ..._generateAuxColors(primary),
  ..._generateBrandColors('primary', primary),
  ..._generateBrandColors('secondary', secondary),
});

export const createWhitelabelTheme = ({
  primary,
  secondary,
  name,
  buttonBorderRadius,
}: ThemeOverrides) => {
  const newTheme = { ...whitelabelDefaults };

  const newColorPalette = _getColorPaletteOverrides(
    whitelabelDefaults.colorPalette,
    primary,
    secondary,
  );

  newTheme.name = name;
  newTheme.colorPalette = newColorPalette;

  if (buttonBorderRadius != null) {
    newTheme.buttonBorderRadius = buttonBorderRadius;
  }
  return newTheme;
};
