import React, { useEffect, forwardRef, useImperativeHandle } from "react";

export interface PureInputProps {
  inputValue: string;
  onChange: (value: any[]) => void;
  onSelect: (value: any[]) => void;
}

const keys = {
  "9": "tab",
  "13": "enter",
};

function getValue(value: string): any[] {
  return value.split("|").map(item => {
    return { name: item.trim() };
  });
}

export const PureInput = forwardRef(function Input(
  { onChange, inputValue, onSelect }: PureInputProps,
  ref
) {
  useEffect(() => {
    // 编辑完成时 inputValue 被置空，此时 onChange 会导致标签键寻找失败
    if (inputValue.trim()) {
      onChange(getValue(inputValue));
    }
  }, [inputValue, onChange]);

  useImperativeHandle(ref, () => ({
    handleKeyDown,
  }));

  function handleKeyDown(keyCode: number): boolean {
    if (!keys[keyCode]) {
      return false;
    }

    switch (keys[keyCode]) {
      case "tab":
      case "enter":
        if (inputValue.length <= 0) return false;
        if (onSelect) {
          onSelect(getValue(inputValue).filter(i => !!i.name));
        }
        return false;
    }
    return false;
  }

  return null;
});
