import React, { memo, useState, useEffect, useCallback } from 'react';
import { connect } from 'react-redux';
import Mousetrap from 'mousetrap';
import { createFavorite } from 'models/favorite';
import FavoriteModal from './FavoriteModal';
import { toObject } from 'utils/layer';
import message from 'components/message';
import styles from './FavoriteModal.less';

function Favorite({ loading, name, thumb, createFavorite }) {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const showModal = (e) => {
      e.preventDefault && e.preventDefault();
      setVisible(true);
    };

    Mousetrap.bind(['command+shift+d', 'ctrl+shift+d'], showModal);
    return () => {
      Mousetrap.unbind(['command+shift+d', 'ctrl+shift+d']);
    };
  }, []);

  const handleCancel = useCallback(() => {
    setVisible(false);
  }, []);

  const handleOk = useCallback(async (values) => {
    const result = await createFavorite(values);
    if (result) {
      message.success(
        <p>
          收藏成功,前往
          <a target="_blank" className={styles.a} href={`${BASENAME}/resource`}>
            资源中心
          </a>
          查看
        </p>
      );
    }
    setVisible(false);
    return result;
  }, []);

  return <FavoriteModal visible={visible} confirmLoading={loading} name={name} thumb={thumb} onCancel={handleCancel} onOk={handleOk} />;
}

const mapStateToProps = ({ favorite, createApp, constants, screensById }) => {
  const { layersSelected, id: screenId } = createApp;
  const screen = screensById[screenId];
  let name, thumb;
  if (screen) {
    const { layers } = screen;
    const { list } = constants;
    const layersById = toObject(layers);
    const selected = layersById[layersSelected[0]];
    name = layersSelected.length === 1 ? selected && selected.name : '未命名分组';
    const constant = list.find((d) => d.moduleName === (selected && selected.moduleName));
    thumb = constant ? constant.thumb : undefined;
  }

  return {
    loading: favorite.editLoading,
    name,
    thumb
  };
};

const mapDispatchToProps = {
  createFavorite
};

export default connect(mapStateToProps, mapDispatchToProps)(memo(Favorite));
