import React, { useCallback, useState, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import classNames from 'classnames';
import SortableList from './SortableList';
import ContextMenu from './ContextMenu';
import styles from './States.less';
import message from 'components/message';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
import { useAuth } from 'components/easyUse';
import { modules } from 'constants/authority';
import { useLocalStorage } from 'components/easyUse';
import { Resizable } from 're-resizable';
import { useSizeByDomId } from 'components/easyUse';

const HEIGHT = 144;

export default function States({ panelId, states, current, onAdd, onDelete, onSort, onNameUpdate, copyState }) {
  const [_states, setStates] = useState(states);
  const [collapsed, setCollapse] = useState(false);
  const [contextVisible, setContextVisible] = useState(false);
  const [contextId, setContextId] = useState(null);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const history = useHistory();
  const location = useLocation();
  const deleteRef = useConfirmRef();
  const { checkAuth } = useAuth();
  const { height: windowHeight = 0 } = useSizeByDomId();
  const [state, setState] = useLocalStorage(panelId);

  useEffect(() => {
    const hideContextMenu = () => {
      setContextVisible(false);
    };

    window.addEventListener('click', hideContextMenu, false);
    return () => {
      window.removeEventListener('click', hideContextMenu, false);
    };
  }, []);

  useEffect(() => {
    setStates(states);
  }, [states]);

  const handleSort = ({ oldIndex, newIndex }) => {
    const copyStates = states.concat();
    const old = copyStates.splice(oldIndex, 1);
    copyStates.splice(newIndex, 0, old[0]);
    setStates(copyStates);
    onSort({ oldIndex, newIndex });
  };

  const handleItemContextMenu = (id, position) => {
    setContextVisible(true);
    setContextId(id);
    setPosition(position);
  };

  const handleAdd = async () => {
    const result = await onAdd();
    if (result) {
      location.pathname.replace(/\/[0-9]+$/, () => {
        return `/${result.id}`;
      });
      history.push(
        location.pathname.replace(/\/[0-9]+$/, () => {
          return `/${result.id}`;
        })
      );
    }
  };

  const handleCopy = async () => {
    const result = await copyState(contextId);
    if (result) {
      history.push(
        location.pathname.replace(/\/[0-9]+$/, () => {
          return `/${result.id}`;
        })
      );
    }
  };

  const handleDelete = () => {
    if (states.length > 1) {
      deleteRef.current?.show();
    } else {
      message.error('必须保留一个状态');
    }
  };

  const handleDeleteConfirm = async () => {
    const result = await onDelete(contextId);
    if (result && current === contextId) {
      const nextState = states.find((d) => d.id !== contextId);
      history.push(
        location.pathname.replace(/\/[0-9]+$/, () => {
          return `/${nextState.id}`;
        })
      );
    }
    setContextId(null);
  };

  const adaptRuler = useCallback((_e, _direction, ref) => {
    const value = parseInt(ref.style.height);
    setState(value);
  }, []);

  return (
    <div>
      <div className={styles.header}>
        <span className={styles.title}>状态</span>
        {checkAuth(modules.componentAdd) && (
          <span className={styles.icon} onClick={handleAdd}>
            <i className="icon iconfont icon-icon_add" />
          </span>
        )}
        <span className={classNames(styles.icon, { [styles.collapsed]: collapsed })} onClick={() => setCollapse(!collapsed)}>
          <i className="icon iconfont icon-icon_fold" />
        </span>
      </div>
      <Resizable
        size={{ width: '100%', height: collapsed ? 0 : state || HEIGHT }}
        enable={{ bottom: true }}
        minHeight={collapsed ? 0 : 64}
        style={{ overflow: 'hidden' }}
        maxHeight={windowHeight - 211}
        onResizeStop={adaptRuler}
        handleClasses={{ bottom: styles.panelSize }}
        handleStyles={{ bottom: { height: 3, bottom: 0 } }}>
        <div className={classNames(styles.content, { [styles.collapsed]: collapsed })}>
          <SortableList
            distance={16}
            items={_states}
            current={current}
            onSortEnd={handleSort}
            onItemContextMenu={handleItemContextMenu}
            updateName={onNameUpdate}
          />
        </div>
      </Resizable>

      {contextVisible && <ContextMenu visible={true} position={position} onCopy={handleCopy} onDelete={handleDelete} />}
      <EasyvModal.Confirm content="此操作执行后不可逆，是否确认删除？" title="提示" onOk={handleDeleteConfirm} ref={deleteRef} />
    </div>
  );
}
