import React, { useCallback, useEffect, useMemo, useState } from 'react';
import style from '../index.less';
import { InputNumber } from '@easyv/antd';
import message from 'components/message';
import { connect } from 'react-redux';
import { spaceItem } from 'models/space.types';
import { updateSpace } from 'models/space';
import isFinite from 'lodash/isFinite';
import toNumber from 'lodash/toNumber';

function HeaderSpace({
  defaultSpace,
  spaceActive,
  spaceList,
  updateSpace
}: {
  defaultSpace: boolean;
  spaceActive: spaceItem;
  spaceList: spaceItem[];
  updateSpace: ({ size: number }) => void;
}): React.ReactElement {
  const [spaceActivVal, setSpaceActivVal] = useState<number>(0);

  const onChange = useCallback(
    (e) => {
      const v = parseInt(e.target.value);
      if (!isFinite(v) || v === spaceActive?.size) {
        setSpaceActivVal(spaceActive?.size);
        return false;
      }
      if (v > maxQuota) {
        message.error('屏幕配额超过上限');
        setSpaceActivVal(spaceActive?.size);
      } else if (v < spaceActive?.screenCount) {
        setSpaceActivVal(spaceActive?.size);
        message.error('空间配额不得少于工作空间内已存在大屏数量');
      } else {
        updateSpace({ size: v });
        setSpaceActivVal(v);
      }
    },
    [spaceActive]
  );

  useEffect(() => {
    setSpaceActivVal(spaceActive?.size);
  }, [spaceActive]);

  const remainingQuota = useMemo(() => {
    const _s: spaceItem | undefined = spaceList.find((d) => !d.type);
    const n = _s ? _s.size - _s.screenCount : 0;
    return n < 0 ? 0 : n;
  }, [spaceActive, spaceList]);

  /**
   * 规则：
   * 1、当剩余配额大于当前空间使用配额，返回剩余配额
   * 2、当剩余空间小于当前空间使用配额，返回当前空间使用配额
   */
  const maxQuota = useMemo(() => {
    return spaceActive?.size + remainingQuota;
  }, [remainingQuota, spaceActive]);

  return (
    <div className={style.headerWrapper}>
      <p className={style.headerTitle}>空间项目配额</p>
      <div className={style.quota}>
        <span>项目配额</span>
        {!defaultSpace && (
          <InputNumber
            className={style.inputNum}
            value={spaceActivVal}
            onPressEnter={(e: any) => e.target.blur()}
            onBlur={onChange}
            onChange={(value) => {
              const v = toNumber(value);
              if (v < 0) {
                setSpaceActivVal(0);
                return false;
              }
              setSpaceActivVal(v);
            }}
          />
        )}
        <span className={style.remaining}>
          剩余配额 <i>{remainingQuota || 0}</i>个
        </span>
      </div>
    </div>
  );
}

function mapStateToProps({ space }) {
  const { active: spaceActive, list: spaceList } = space;
  return {
    spaceActive,
    spaceList
  };
}

export default connect(mapStateToProps, {
  updateSpace
})(HeaderSpace);
