import React, { useState, useEffect } from 'react';
import { Card } from 'antd';
import { omit, keys, values } from 'lodash';
import cs from 'classnames';
import produce from 'immer';
import { CheckCircleOutlined } from '@ant-design/icons';
import Trigger from './trigger';
import Hocs from '../../components/hocs';
import { PREFIX_CLS } from '../../config';
import './index.less';

const prefixCls = `${PREFIX_CLS}-animate-editor`;
const animations = [
  {
    text: '无',
    title: '无动画',
  },
  {
    init: {
      scale: 1,
    },
    event: 'hover',
    name: 'scale',
    text: '缩放',
    title: '大小缩放',
    duration: 0.1,
    scale: 1.2,
  },
];
const defaultAnimation = animations[0];
const gridStyle = {
  width: '25%',
  textAlign: 'center',
};

export default ({ onChangePathValue = () => {}, node, propKey }) => {
  const monitor = node[propKey];
  const [animation, setAnimation] = useState(defaultAnimation);

  const handleTriggerChange = params => {
    const nextAnimation = produce(animation, draft => {
      Object.assign(draft, params);
    });
    setAnimation(nextAnimation);
    onChangePathValue({ path: keys(params), value: values(params) });
  };

  const handleTemplateClick = params => {
    setAnimation(params);
    onChangePathValue({
      path: 'animation',
      value: omit(params, ['text', 'title']),
      custom: true,
    });
  };

  useEffect(() => {
    setAnimation(monitor || defaultAnimation);
  }, [monitor]);

  return (
    <>
      <Card title={null}>
        {animations.map(item => {
          const isEmpty = !item.name;
          const checked = item.name === animation.name;
          return (
            <Card.Grid
              hoverable={false}
              style={gridStyle}
              onClick={() => {
                handleTemplateClick(item);
              }}
            >
              <div className={prefixCls}>
                <div
                  className={cs(
                    `${prefixCls}__example`,
                    checked ? `${prefixCls}__example--active` : '',
                  )}
                >
                  <Hocs animation={{ ...item, event: 'hover' }}>
                    <div
                      className={cs(
                        `${prefixCls}__box`,
                        isEmpty ? `${prefixCls}__box--empty` : '',
                      )}
                    >
                      {item.text}
                    </div>
                  </Hocs>

                  {checked && (
                    <CheckCircleOutlined className={`${prefixCls}__icon`} />
                  )}
                </div>

                <div className={`${prefixCls}__title`}>{item.title}</div>
              </div>
            </Card.Grid>
          );
        })}
      </Card>
      <div style={{ marginTop: 15 }}>
        {Object.keys(animation).length > 0 && (
          <Trigger animation={animation} onChange={handleTriggerChange} />
        )}
      </div>
    </>
  );
};
