import React, { useMemo } from 'react'
import { SkeletonProps, SkeletonSizes, SkeletonUnits } from './skeleton-types'
import useTheme from '../use-theme'

const getSkeletonSize = (size?: SkeletonSizes, unit?: SkeletonUnits) => {
  const safeUnit = unit || 'vw'
  switch (size) {
    case 'mini':
      return `5${safeUnit}`
    case 'small':
      return `10${safeUnit}`
    case 'large':
      return `40${safeUnit}`
    default:
      return `25${safeUnit}`
  }
}

const Skeleton: React.FC<SkeletonProps> = ({ size, unit }) => {
  const theme = useTheme()
  const width = useMemo(() => getSkeletonSize(size, unit), [size, unit])
  return (
    <>
      <span className="skeleton-box" style={{ width }} />
      <style jsx>{`
        .skeleton-box {
          display: inline-block;
          height: 0.75em;
          position: relative;
          overflow: hidden;
          background-color: ${theme.palette.secondary};
          opacity: 8%;
          border-radius: 2px;

          /* Set blend mode to fix rendering issue on Google Chrome */
          mix-blend-mode: luminosity;
        }
        .skeleton-box::after {
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          transform: translateX(-100%);
          background-image: -webkit-gradient(
            linear,
            left top,
            right top,
            color-stop(0, rgba(255, 255, 255, 0)),
            color-stop(20%, rgba(255, 255, 255, 0.2)),
            color-stop(60%, rgba(255, 255, 255, 0.5)),
            to(rgba(255, 255, 255, 0))
          );
          background-image: linear-gradient(
            90deg,
            rgba(255, 255, 255, 0) 0,
            rgba(255, 255, 255, 0.2) 20%,
            rgba(255, 255, 255, 0.5) 60%,
            rgba(255, 255, 255, 0)
          );
          animation: shimmer 2s infinite;
          content: '';
        }
        /* 
          FIXME: Shimmer effect leads to high CPU usage on MacOS
        @keyframes shimmer {
          100% {
            transform: translateX(100%);
          }
        }
         */
      `}</style>
    </>
  )
}

export default Skeleton
