import React, { useCallback, useEffect, useMemo, useState } from 'react';
import styles from './index.less';
import { screenEditModel } from 'models/screen-edit';
interface Switchs {
  name: string;
  value: number | string;
}

const defaultSwitchs = [
  {
    value: screenEditModel.CANVAS,
    name: '画布编辑'
  },
  {
    value: screenEditModel.NODES,
    name: '节点管理'
  }
];

function EasyvSwitch({
  value = screenEditModel.CANVAS,
  switchs = defaultSwitchs,
  onChange
}: {
  value?: number | string;
  switchs?: Switchs[];
  onChange?: (x) => void;
}) {
  const [index, setIndex] = useState(0);
  const [current, setVal] = useState(value);
  const newSwitchs: Switchs[] = useMemo(() => {
    return switchs.filter((d) => d).filter((d, i) => i < 2);
  }, [switchs]);

  const initIndex = useCallback(
    (value) => {
      const i = newSwitchs.findIndex((d) => d.value === value);
      setIndex(i);
    },
    [newSwitchs]
  );

  useEffect(() => {
    // 初始化
    setVal(value);
    initIndex(value);
  }, [value]);

  const handleClick = (value) => {
    setVal(value);
    initIndex(value);
    onChange?.(value);
  };

  return (
    <div className={styles.easyvSwitch}>
      <ul className={`${styles.activate} ${styles[`activate-${index}`] || ''}`}>
        {newSwitchs
          .filter((d) => d)
          .map((d) => (
            <li
              className={d.value === current ? styles.liAction : ''}
              key={d.value}
              onClick={() => {
                handleClick(d.value);
              }}>
              <span>{d.name}</span>
            </li>
          ))}
      </ul>
    </div>
  );
}

export default EasyvSwitch;
