// @flow
import type { ThemeProps } from '../../types';
import type { PatchworkTheme } from '../../themes/theme.types';
import type { SpaceProps, SpaceValue } from './spacing.proptypes';
import { bpMedium, bpLarge, bpXLarge } from '../../breakpoints';

const _getSpacingAmount = (
  theme: PatchworkTheme,
  regex: RegExp,
  key: SpaceValue,
) => {
  const keys = Array.isArray(key) ? key : [key];
  const heightKeys = keys.filter((k) => regex.test(k));

  // First one wins in case of conflict.
  if (!heightKeys[0]) {
    return;
  }
  const regexResult = regex.exec(heightKeys[0]);
  if (regexResult === null) return '0';
  const [, level] = regexResult;
  if (level === '0' || level === 'auto') {
    return level;
  }
  return level != null ? theme.spacing[`s${level}`] : '0';
};

const _getSpacingTop = (
  theme: PatchworkTheme,
  key: SpaceValue,
  mOrP: 'm' | 'p',
) =>
  _getSpacingAmount(
    theme,
    mOrP === 'm' ? /^m[vt]?([0-9])$/ : /^p[vt]?([0-9])$/,
    key,
  );

const _getSpacingRight = (
  theme: PatchworkTheme,
  key: SpaceValue,
  mOrP: 'm' | 'p',
) =>
  _getSpacingAmount(
    theme,
    mOrP === 'm' ? /^m[hr]?([0-9]|auto)$/ : /^p[hr]?([0-9])$/,
    key,
  );

const _getSpacingBottom = (
  theme: PatchworkTheme,
  key: SpaceValue,
  mOrP: 'm' | 'p',
) =>
  _getSpacingAmount(
    theme,
    mOrP === 'm' ? /^m[vb]?([0-9]|auto)$/ : /^p[bv]?([0-9])$/,
    key,
  );

const _getSpacingLeft = (
  theme: PatchworkTheme,
  key: SpaceValue,
  mOrP: 'm' | 'p',
) =>
  _getSpacingAmount(
    theme,
    mOrP === 'm' ? /^m[hl]?([0-9]|auto)$/ : /^p[hl]?([0-9])$/,
    key,
  );

const getSpacingOptions = (
  theme: PatchworkTheme,
  spacing: SpaceValue,
): string => {
  if (!spacing) {
    return '';
  }

  // Set spacing for all breakpoints.
  const marginTop = _getSpacingTop(theme, spacing, 'm');
  const marginRight = _getSpacingRight(theme, spacing, 'm');
  const marginBottom = _getSpacingBottom(theme, spacing, 'm');
  const marginLeft = _getSpacingLeft(theme, spacing, 'm');
  const paddingTop = _getSpacingTop(theme, spacing, 'p');
  const paddingRight = _getSpacingRight(theme, spacing, 'p');
  const paddingBottom = _getSpacingBottom(theme, spacing, 'p');
  const paddingLeft = _getSpacingLeft(theme, spacing, 'p');

  const rules = [];
  if (marginTop) {
    rules.push(`margin-top: ${marginTop};`);
  }
  if (marginRight) {
    rules.push(`margin-right: ${marginRight};`);
  }
  if (marginBottom) {
    rules.push(`margin-bottom: ${marginBottom};`);
  }
  if (marginLeft) {
    rules.push(`margin-left: ${marginLeft};`);
  }
  if (paddingTop) {
    rules.push(`padding-top: ${paddingTop};`);
  }
  if (paddingRight) {
    rules.push(`padding-right: ${paddingRight};`);
  }
  if (paddingBottom) {
    rules.push(`padding-bottom: ${paddingBottom};`);
  }
  if (paddingLeft) {
    rules.push(`padding-left: ${paddingLeft};`);
  }

  return rules.join('\n');
};

// For embedding in a template string.
export const getSpacingRules = ({
  theme,
  spacing,
}: {|
  ...ThemeProps,
  ...SpaceProps,
|}): string => {
  if (!spacing) {
    return '';
  }

  if (typeof spacing === 'string' || Array.isArray(spacing)) {
    return getSpacingOptions(theme, spacing);
  }

  const rules = [];
  if (spacing.sm != null) {
    rules.push(
      `@media (max-width: ${bpMedium}) {${getSpacingOptions(
        theme,
        spacing.sm,
      )}}`,
    );
  }

  if (spacing.md != null) {
    rules.push(
      `@media (min-width: ${bpMedium}) {${getSpacingOptions(
        theme,
        spacing.md,
      )}}`,
    );
  }

  if (spacing.lg != null) {
    rules.push(
      `@media (min-width: ${bpLarge}) {${getSpacingOptions(
        theme,
        spacing.lg,
      )}}`,
    );
  }

  if (spacing.xl != null) {
    rules.push(
      `@media (min-width: ${bpXLarge}) {${getSpacingOptions(
        theme,
        spacing.xl,
      )}}`,
    );
  }

  return rules.join('\n');
};
