import {
  h, Component, useRef, useState, useEvent,
} from "atomico";
import style from "./kun-file-select.scss";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";

const KunFileSelect = () => {
  const [name, setName] = useState("");
  const inputRef = useRef<HTMLInputElement>();

  const onMyFileChange = useEvent("MyFileChange", {
    composed: true,
    bubbles: true,
  });

  const setFile = (evt): void => {
    const fileInput: File = evt.target.files[0];
    if (fileInput != null) {
      setName(fileInput.name);
      onMyFileChange(fileInput);
    }
  };

  const onSelect = (): void => {
    inputRef.current.click();
  };
  return (
    <host>
      <style>{style}</style>
      <div
        onclick={onSelect}
        className="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline cursor-pointer"
      >
        {name.length === 0 ? "请选择文件" : name}
      </div>
      <input
        className="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline hidden"
        type="file"
        ref={inputRef}
        onchange={setFile}
      />
    </host>
  );
};

export default getComponentOrDefine("kun-file-select", KunFileSelect);
