import { Transition } from 'react-transition-group';
import { TimeoutProps } from 'react-transition-group/Transition';
import React, { CSSProperties, ReactElement } from 'react';
import classNames from 'classnames';

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

export function Rotate({
  children,
  timeout,
  deg: degProp,
  ...rest
}: RotateProps) {
  const { type: Component, props: childProps } = children;

  return (
    <Transition timeout={timeout} {...rest}>
      {(status) => {
        const deg = status === 'exited' || status === 'exiting' ? degProp : 0;

        const style = {
          transitionProperty: 'transform',
          transitionDuration: `${timeout}ms`,
          transitionTimingFunction: 'ease-in',
          transform: `rotate(${deg}deg)`,
          ...rest.style,
          ...childProps.style,
        };

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