import React, { memo, useRef } from 'react';
import { connect } from 'react-redux';
import Thumb from 'components/Thumb';
import styles from './Item.less';
import EditContainer from 'containers/admin-panel/components/themePanel/EditContainer';
import { updateVersion } from 'models/updateVersion';
import IconButton from 'components/IconButton';
import { useProductionInfo } from 'components/easyUse';
import classNames from 'classnames';
import { getAssetsUrl } from 'utils/utils';

function ThemeItem({
  id,
  name,
  thumb,
  lock,
  isDefault = false,
  onClick,
  updateVersion,
}: {
  id?: number;
  name: string;
  thumb: string;
  lock?: boolean;
  isDefault?: boolean;
  onClick: (id?: number) => any;
  updateVersion: ({}) => any;
}) {
  const itemRef = useRef<HTMLDivElement>(null);
  const isLocal = window.appConfig.LOCAL;
  const productionInfo = useProductionInfo();
  const { isRoot, isRenew } = productionInfo;
  const handleApply = (e) => {
    if (itemRef.current?.contains(e.target)) {
      if (lock) {
        updateVersion({ show: true });
      } else {
        onClick(id);
      }
    }
    // WARNING 不大能看明白isFastCreateIntro是不是代表第一次创建intro，目前猜测是第一次创建intro的意思
  };

  return (
    <div ref={itemRef} className={styles.container} onClick={handleApply}>
      <div className={styles.thumb}>
        <Thumb
          src={thumb ? getAssetsUrl(thumb) : undefined}
          style={{ width: '100%', height: '100%' }}
        />
        {id && isRoot && (
          <EditContainer
            id={id}
            name={name}
            thumb={thumb}
            published={true}
            isDefault={isDefault}
            coverShow={true}>
            <span className={styles.edit}>
              <i className={classNames('icon iconfont icon-bianji ')} />
            </span>
          </EditContainer>
        )}
        {!isLocal && id ? (
          <IconButton
            className={styles.saas_vip_icon}
            type={isRenew ? 'renew_advanced' : 'saas_advanced'}
          />
        ) : null}
      </div>
      <span className={styles.name}>{name}</span>
    </div>
  );
}

const mapDispatchToProps = {
  updateVersion,
};

export default connect(null, mapDispatchToProps)(memo(ThemeItem));
