// @flow
import { compact } from 'lodash';
import type { ThemeProps } from '../../types';
import type { PatchworkTheme } from '../../themes/theme.types';
import type {
  SpaceProps,
  SpaceValue,
  ResponsiveSpaceValue,
} from './spacing.proptypes';
import {
  bpMedium,
  bpLarge,
  bpXLarge,
  type BreakPoint,
  breakPoints,
} 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';
};

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

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

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

export 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 || spacing.sm != null) {
    rules.push(
      `@media (min-width: ${bpMedium}) {${getSpacingOptions(
        theme,
        spacing.md || spacing.sm,
      )}}`,
    );
  }

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

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

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

const getEffectiveBreakPoint = (
  spacing: ResponsiveSpaceValue,
  currentBreakpoint: BreakPoint,
): BreakPoint => {
  const currentIndex = breakPoints.findIndex((bp) => bp === currentBreakpoint);
  const candidateBreakPoints = compact(
    breakPoints
      .slice(0, currentIndex + 1)
      .filter((bp) => !!spacing[bp])
      .reverse(),
  );

  return candidateBreakPoints[0] ?? 'sm';
};

// Gets the space value that's active in the current breakpoint.
export const getEffectiveSpaceValue = (
  spacing?: SpaceValue | ResponsiveSpaceValue,
  currentBreakpoint: BreakPoint,
): SpaceValue | void => {
  if (
    spacing == null ||
    typeof spacing === 'string' ||
    Array.isArray(spacing)
  ) {
    return spacing;
  }

  return spacing[getEffectiveBreakPoint(spacing, currentBreakpoint)];
};
