import {
  Component, h, useProp, useState,
} from "atomico";
// eslint-disable-next-line no-unused-vars
import produce, { Draft } from "immer";
import "../kun-edit-tag/kun-edit-tag";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";

interface ChangeEvent<T> {
    target: HTMLInputElement;
}

const KunTagInput = () => {
  const [tags, setTags] = useProp<string[]>("tags");
  const [maxSize] = useProp<number>("maxSize");
  const [currentTag, setCurrentTag] = useState<string>("");

  const deleteTag = (tag: string): void => {
    const s1 = produce(tags, (draft: Draft<string>[]) => {
      const index = tags.findIndex((item) => item === tag);
      if (index > -1) {
        draft.splice(index, 1);
      }
    });
    setTags(s1);
  };

  const addTag = (): void => {
    if (currentTag !== "") {
      if (tags.indexOf(currentTag) < 0) {
        setTags((tags.concat(currentTag)));
      }
      setCurrentTag("");
    }
  };

  const changeInput = (event: ChangeEvent<HTMLInputElement>): void => {
    const { value } = event.target;
    setCurrentTag(value);
  };
  return (
    <host>
      <style>{mockStyle}</style>
      <div className="flex ">
        <div>
          {
                        tags.map((item: string) => (
                          <kun-edit-tag
                            className="mr-4"
                            content={item}
                            onDeleteTag={() => deleteTag(item)}
                          />
                        ))
                    }
        </div>

        {
                    (tags.length < maxSize) && (
                    <div className="inline-flex w-1/3 justify-end items-center">
                      <input
                        type="text"
                        className="border-b-2  px-2 focus:shadow-outline focus:bg-blue-100 mr-3"
                        value={currentTag}
                        oninput={changeInput}
                      />
                      <button classNamee="px-4 bg-gray-300 hover:bg-gray-400 text-gray-800" onclick={addTag} type="button">
                        添加
                      </button>
                    </div>
                    )
                }
      </div>
    </host>
  );
};

KunTagInput.props = {
  max: {
    type: Number,
    value: 5,
  },
};

export default getComponentOrDefine("kun-tag-input", KunTagInput);
