import React, { useRef, useEffect } from 'react';
import classNames from 'classnames';
import UsedCondition from './UsedCondition';
import { Input } from '@easyv/react-gui';
import styles from './ItemHeader.less';

export default function ItemHeader({
  className,
  name,
  editable,
  unsaved,
  collapsed,
  usedComponents,
  onCollapsedChange,
  onNameChange,
  onEditChange,
  onDelete
}: {
  className?: string;
  name: string;
  editable: boolean;
  unsaved: boolean;
  collapsed: boolean;
  usedComponents?: any[];
  onCollapsedChange: (collapsed) => any;
  onNameChange: (name) => any;
  onEditChange: (edit) => any;
  onDelete: () => any;
}) {
  const inputRef = useRef<Input>(null);

  useEffect(() => {
    if (editable) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [editable]);

  const handleEditChange = (e) => {
    e.stopPropagation();
    onEditChange(true);
  };

  const handleDelete = (e) => {
    e.stopPropagation();
    onDelete();
  };

  return (
    <div className={classNames(styles.container, className)} onClick={() => onCollapsedChange(!collapsed)}>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <span className={classNames(styles.collapse, { collapsed: collapsed })}>
          <i className="icon iconfont icon-icon_fold " />
        </span>

        <span className={styles.name}>
          {editable ? (
            <>
              <Input
                ref={inputRef}
                value={name}
                onChange={(e) => onNameChange(e.target.value)}
                onClick={(e) => e.stopPropagation()}
                onPressEnter={(e) => e.target.blur()}
                onBlur={() => onEditChange(false)}
              />
            </>
          ) : (
            <span title={name}>{name}</span>
          )}
        </span>

        <span className={styles.edit} onClick={handleEditChange}>
          <i className="icon iconfont icon-icon_edit" />
        </span>

        {unsaved && (
          <span className={styles.status}>
            <i className={styles.icon} />
            未保存
          </span>
        )}
      </div>

      <div style={{ display: 'flex', alignItems: 'center' }}>
        <UsedCondition usedComponents={usedComponents} />

        <span className={styles.delete} onClick={handleDelete}>
          <i className="icon iconfont icon-btn_delete" />
        </span>
      </div>
    </div>
  );
}
