import { css, CSSProperties, keyframes } from 'glamor';
import { observer } from 'mobx-react';
import { useApphouse } from '../context/useApphouse';
import { LoadingStyles } from '../styles/defaults/themes.interface';
import React from 'react';
import { setAlpha } from '../utils/color/setAlpha';
import { mergeStyles } from '..';
/**
 * THeY See ME rollin' they hatin'
 */
const spin = keyframes('spin', {
  '0%': {
    transform: 'rotate(0deg)'
  },
  '100%': {
    transform: 'rotate(360deg)'
  }
});

export interface LoadingProps {
  /**
   * Color scheme to be used in the loader
   * it has to be a hex value
   */
  hexColor?: string;
  /**
   * The width of the loading indicator.
   * @default  4
   */
  thickness?: number;
  /**
   * @default 25
   */
  size?: number;
  /**
   * Style of the loading indicator
   * @default LoadingStyles.default
   */
  variant?: keyof LoadingStyles;
  /**
   * Any style overwrites you might want to use
   */
  styleOverwrites?: CSSProperties;
}
export const Loading: React.FC<LoadingProps> = observer(
  ({
    hexColor,
    thickness = 4,
    size = 25,
    variant = 'circular',
    styleOverwrites = {}
  }) => {
    const { theme } = useApphouse();
    const { styles } = theme;
    const componentStyles = styles.loading[variant];
    const localOverwrites = {};

    if (
      variant === 'circular' &&
      (thickness !== undefined || size !== undefined || hexColor !== undefined)
    ) {
      const colorIndicator = hexColor || componentStyles.borderColor;
      styleOverwrites = {
        borderWidth: `${thickness}px`,
        borderStyle: 'solid',
        borderColor: colorIndicator,
        borderRadius: '50%',
        borderTop: `${thickness}px solid ${setAlpha(colorIndicator, 0.5)}`,
        width: size,
        height: size,
        animation: `${spin} 2s linear infinite`
      };
    }

    const cStyles = mergeStyles(styles.loading[variant], localOverwrites);
    const localStyles = mergeStyles(cStyles, styleOverwrites);
    return <div {...css(localStyles)}></div>;
  }
);
