import { css, CSSProperties, keyframes } from 'glamor';
import { observer } from 'mobx-react';
import React from 'react';
import { mergeStyles, useApphouse } from '..';
import { ApphouseComponent } from '../components/component.interfaces';
import { getGradientBoxShadow } from '../styles/getGradientBoxShadow';

export interface LoadingGradientStyles {
  spinner?: CSSProperties;
  spinnerIn?: CSSProperties;
}

const rot55 = keyframes({
  to: {
    transform: `rotate(360deg)`
  }
});

export const getLoadingGradientStyles = (
  size: number,
  colors: string[],
  speed = 0.7
): LoadingGradientStyles => {
  const s = `${size}em`;
  const sh = `${size / 2}em`;
  const boxShadow = getGradientBoxShadow(colors);

  return {
    spinner: {
      width: s,
      height: s,
      cursor: 'not-allowed',
      borderRadius: '50%',
      boxShadow: boxShadow,
      animation: `${rot55} ${speed}s linear infinite`
    },
    spinnerIn: {
      width: sh,
      height: sh,
      borderRadius: '50%',
      position: 'absolute',
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)'
    }
  };
};

export interface LoadingGradientProps
  extends ApphouseComponent<LoadingGradientStyles> {
  /**
   * The colors to use for the gradient.
   * Up to 7 colors can be specified.
   * @default ["brand"]
   */
  colors?: string[];
  /**
   * @default 3
   */
  size?: number;
  /**
   * The speed of the animation.
   * @default 0.7s
   * @optional
   */
  speed?: number;
}
export const LoadingGradient: React.FC<LoadingGradientProps> = observer(
  ({ colors: _colors = [], speed = 0.7, size = 3, styleOverwrites }) => {
    const { theme } = useApphouse();
    const colors = _colors.length ? _colors : [theme.colors.brand];
    const localStyles = mergeStyles<LoadingGradientStyles>(
      getLoadingGradientStyles(size, colors, speed),
      styleOverwrites
    );
    return (
      <div {...css(localStyles.spinner)}>
        <div {...css(localStyles.spinnerIn)}></div>
      </div>
    );
  }
);
