import {
  useColorModeValue,
  Spinner as BaseSpinner,
  ThemeTypings,
  SpinnerProps as BaseSpinnerProps,
  Center,
  Box,
} from '@chakra-ui/react';

import React, { FC, useMemo } from 'react';

export interface SpinnerProps extends BaseSpinnerProps {
  /** 是否加载中 */
  isSpinning?: boolean;

  /** 旋转器中空白区域的颜色 */
  emptyColor?: string;

  /** 旋转器的粗细 */
  thickness?: string;

  /** 旋转器的速度 */
  speed?: string;

  /** 对于可访问性，添加回退加载文本非常重要。此文本将对屏幕阅读器可见。 */
  label?: string;

  /** 旋转器的大小 */
  size?: ThemeTypings['components']['Spinner']['sizes'];
}

const Spinner: FC<SpinnerProps> = ({ children, isSpinning = true, ...props }) => {
  const color = useColorModeValue('blue.500', 'blue.200');
  const emptyColor = useColorModeValue('gray.200', 'gray.800');

  const isNestedPattern = useMemo(() => typeof children !== 'undefined', [children]);

  if (isNestedPattern) {
    return (
      <div style={{ position: 'relative' }}>
        <Box
          pos="relative"
          transition="opacity 0.3s"
          {...(isSpinning
            ? { opacity: 0.5, pointerEvents: 'none', userSelect: 'none' }
            : undefined)}
        >
          {children}
        </Box>
        {isSpinning && (
          <Center pos="absolute" top={0} left={0} width="100%" height="100%">
            <BaseSpinner thickness="4px" color={color} emptyColor={emptyColor} {...props} />
          </Center>
        )}
      </div>
    );
  }

  return <BaseSpinner thickness="4px" color={color} emptyColor={emptyColor} {...props} />;
};

export default Spinner;
