import { ColorName } from '@emotion/react';
import { Container, StyleSystemThemedProps } from 'components/layout';
import { MotiView } from 'moti';
import { useEffect, useRef, useState } from 'react';

export const ProgressCircle: React.FC<ProgressCircleType> = ({
  size,
  children,
  directionVariant,
  colorVariant,
  ...props
}) => {
  const [downloaded, setDownloaded] = useState(0);
  const progressBarRef = useRef<NodeJS.Timer>();

  useEffect(() => {
    progressBarRef.current = setInterval(() => {
      setDownloaded((state) => state + 1);
    }, 50);

    return () => {
      if (progressBarRef.current) {
        clearInterval(progressBarRef.current);
      }
    };
  }, []);

  useEffect(() => {
    if (downloaded >= 100) {
      if (progressBarRef.current) {
        clearInterval(progressBarRef.current);
      }
    }
  }, [downloaded]);

  const height = directionVariant == 'horizontal' ? size : '100%';
  const motiHeight = directionVariant == 'horizontal' ? undefined : downloaded;
  const width = directionVariant == 'horizontal' ? undefined : size;
  const motiWidth = directionVariant == 'horizontal' ? downloaded : undefined;

  return (
    <MotiView
      animate={{
        width: motiWidth,
        height: motiHeight,
        opacity: 1,
      }}
      delay={200}
      from={{
        width: width,
        height: height,
        opacity: 1,
      }}
      style={{
        overflow: 'hidden',
        backgroundColor: colorVariant,
      }}
    >
      <Container
        height={height}
        width={width}
        backgroundColor={colorVariant}
        borderRadius={10}
        {...props}
      >
        {children}
      </Container>
    </MotiView>
  );
};

export type ProgressCircleType = ProgressCircleProps & StyleSystemThemedProps;
export type ProgressCircleDirection = 'vertical' | 'horizontal';
export interface ProgressCircleProps {
  colorVariant: ColorName;
  size: number;
  children?: JSX.Element;
  directionVariant: ProgressCircleDirection;
}
