import { Children, cloneElement } from 'react';
import classnames from 'classnames';
import css from 'styled-jsx/css';

import type { FC, ReactNode } from 'react';

interface FadeOnMountProps {
  delay?: number;
  duration?: number;
  bypass?: boolean;
  children: ReactNode;
}

const sjsx = css.resolve`
  .fadeOnMount {
    animation-name: fadeIn;
    animation-duration: 300ms;
    animation-delay: 100ms;
    animation-fill-mode: forwards;
    opacity: 0;
  }

  @keyframes fadeIn {
    0% {
      opacity: 0;
    }
    100% {
      opacity: 1;
    }
  }
`;

const FadeOnMount: FC<FadeOnMountProps> = ({
  children,
  delay = 100,
  duration = 400,
  bypass = false,
}) => {
  const child = Children.only<any>(children);

  const { className, style, ...restChildProps } = child.props;

  const styleInternal = {
    ...style,
    animationDuration: `${duration}ms`,
    animationDelay: `${delay}ms`,
  };

  const childClone = cloneElement(child, {
    ...restChildProps,
    className: classnames(className, 'fadeOnMount', sjsx.className),
    style: styleInternal,
  });

  if (bypass) return <>{children}</>;

  return (
    <>
      {childClone}
      {sjsx.styles}
    </>
  );
};

export default FadeOnMount;
