import { Transition } from 'react-transition-group';
import { TimeoutProps } from 'react-transition-group/Transition';
import React, { CSSProperties, ReactElement, useMemo } from 'react';
import { st, classes } from './Fade.st.css.js';

export interface FadeProps extends TimeoutProps<undefined> {
  children: ReactElement<{ className?: string; style?: CSSProperties }>;
}

export function Fade({ children, timeout, ...rest }: FadeProps) {
  const { type: Component, props: childProps } = children;
  const style = useMemo(
    () => ({
      transitionDuration: `${timeout}ms`,
      ...childProps.style,
    }),
    [timeout, childProps.style],
  );

  return (
    <Transition timeout={timeout} {...rest}>
      {(status) => {
        const className = st(
          classes.root,
          {
            exit: status === 'exited' || status === 'exiting',
          },
          childProps.className,
          `fade-${status}`,
        );

        return (
          <Component {...childProps} className={className} style={style} />
        );
      }}
    </Transition>
  );
}
