import React from 'react'
import { keyframes } from '@emotion/react'
import styled from '@emotion/styled'
import { lightTheme } from 'app/constants/theme'

const svgAnimation = keyframes`
  0% {
    transform: rotateZ(0deg);
  }
  100% {
    transform: rotateZ(360deg)
  }
`

const circleAnimation = keyframes`
  0%,
  25% {
    stroke-dashoffset: 280;
    transform: rotate(0);
  }

  50%,
  75% {
    stroke-dashoffset: 75;
    transform: rotate(45deg);
  }

  100% {
    stroke-dashoffset: 280;
    transform: rotate(360deg);
  }
`

const LoadingIcon = (props: StyledLoadingIconProps) => (
  <svg viewBox="0 0 100 100" {...props}>
    <circle cx="50" cy="50" r="42" />
  </svg>
)

type StyledLoadingIconProps = {
  size?: 'large' | 'small'
  color?: keyof typeof lightTheme.colors
}

const StyledLoadingIcon = styled(LoadingIcon)<StyledLoadingIconProps>(
  ({ size = 'small', color = 'icon' }) => ({
    width:
      size === 'small' ? lightTheme.base.gutter(2) : lightTheme.base.gutter(4),
    height:
      size === 'small' ? lightTheme.base.gutter(2) : lightTheme.base.gutter(4),
    animation: `2s linear infinite ${svgAnimation} `,

    circle: {
      animation: `1.4s ease-in-out infinite both ${circleAnimation}`,
      display: 'block',
      fill: 'transparent',
      stroke: (lightTheme.colors[color] ?? lightTheme.colors.icon) as string,
      strokeLinecap: 'round',
      strokeDasharray: 283,
      strokeDashoffset: 75,
      strokeWidth: 16,
      transformOrigin: '50% 50%',
    },
  })
)

export const LoadingIconPrimary = (
  props: StyledLoadingIconProps
): React.ReactElement => <StyledLoadingIcon {...props} color="primary" />

export const LoadingIconWhite = (
  props: StyledLoadingIconProps
): React.ReactElement => <StyledLoadingIcon {...props} color="loadingIcon" />

export default StyledLoadingIcon
