import React, { useState, useCallback, useEffect } from 'react';
import { Motion, spring } from 'react-motion';
import { getAnimateStyle } from './handler';
import { EventType } from '../../utils/system';
import Inner from './inner';

const properties = ['x', 'y', 'scale'];
export default ({ children, animation, link = {}, width, height }) => {
  const { init = { scale: 1 }, event, stiffness = 170, damping = 26 } =
    animation || {};
  const [visible, setVisible] = useState(event === EventType.INIT);
  const [stateAnimateStyle, setStateAnimateStyle] = useState({});
  const enter = useCallback(() => {
    setVisible(true);
  });
  const leave = useCallback(() => {
    setVisible(false);
  });
  let onMouseEnter;
  let onMouseLeave;
  let onClick;
  switch (event) {
    case EventType.HOVER:
      onMouseEnter = enter;
      onMouseLeave = leave;
      break;
    case EventType.CLICK:
      onClick = enter;
      break;
    default:
      break;
  }

  useEffect(() => {
    if (animation) {
      const style = {};
      properties.forEach(key => {
        if (animation[key] !== undefined) {
          style[key] = spring(visible ? animation[key] : init[key], {
            stiffness,
            damping,
          });
        }
      });
      setStateAnimateStyle(style);
    }
  }, [visible, animation]);

  return animation ? (
    <Motion defaultStyle={init} style={stateAnimateStyle}>
      {dynAnimate => {
        const nextStyle = getAnimateStyle(dynAnimate);
        return (
          <Inner
            style={{ width, height, ...nextStyle }}
            link={link}
            onMouseEnter={onMouseEnter}
            onMouseLeave={onMouseLeave}
            onClick={onClick}
            isAnimated
          >
            {children}
          </Inner>
        );
      }}
    </Motion>
  ) : (
    <Inner style={{ width, height }} link={link}>
      {children}
    </Inner>
  );
};
