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

const array = [
  "😀",
  "😬",
  "😁",
  "😂",
  "🤣",
  "😃",
];

const KunEmojiPicker = () => {
  const onEvent = useEvent("SelectEvent", { bubbles: true, composed: true });
  const buttonRef = useRef<HTMLElement>();
  const [loaded, setLoaded] = useState(false);
  const b = useRef<HTMLElement>();

  useEffect(() => {
    // console.log('b.cu', b.current)
    // buttonRef.current.parent = b.current;
    console.log("b.cu", b.current);
    if (b.current != null) {
      setLoaded(true);
    }
  }, [b.current]);

  const onClick = (item: MouseEvent): void => {
    const a = (item.target as HTMLElement);
    const regex = new RegExp(/<% emojiSequence %>|\p{Emoji_Presentation}|\p{Emoji}\uFE0F?|\p{Emoji_Modifier_Base}/gu);
    const r = a.innerHTML.match(regex)[0];
    if (r !== "6") {
      onEvent({ data: r });
    }
    // TODO emit erray
  };

  const clickButtonEvent = (event: MouseEvent): void => {
    buttonRef.current?.show();
    event.preventDefault();
  };

  return (
    <host>
      <style>{style}</style>
      <div className="relative">
        <rb-popover position="bottom" icon-kind="smile" kind="neutral" icon-size={1.2}>
          <div class="w-64 flex flex-wrap justify-center pt-2">
            {
                array.map((item, index) => (
                  <div
                    key={String(index)}
                    onclick={(e) => onClick(e)}
                    className="cursor-pointer pr-2 mb-4
               border-solid mx-5 border-1 border-gray-200 text-2xl"
                  >
                    <span>{item}</span>
                  </div>
                ))
              }
          </div>
        </rb-popover>
      </div>
    </host>
  );
};

export default getComponentOrDefine("kun-emoji-picker", KunEmojiPicker);
