import {
  h, useEffect, useEvent, useProp, useRef, useState,
} from "atomico";
import style from "./kun-fold-button.scss";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";
import { isChildOf } from "../kun-dropdown/kun-dropdown";

const KunFoldButton = () => {
  const [showDialog, setShowDialog] = useState(false);
  const [kunTitle] = useProp<string>("kunTitle");
  const ref = useRef<HTMLElement>();

  const onMyClick = useEvent("MyClick", {
    composed: true,
    bubbles: true,
  });
  const onClick = (event: MouseEvent): void => {
    if (showDialog) {
      setShowDialog(false);
    } else {
      setShowDialog(true);
    }
    onMyClick({});
    event.preventDefault();
    event.stopPropagation();
  };

  const clickEventI = (event: MouseEvent): void => {
    if (
      event.target != null
        && !isChildOf(event.target as HTMLElement, ref.current!)
    ) {
      if (showDialog) {
        setShowDialog(false);
        event.preventDefault();
      }
    }
  };

  useEffect(() => {
    document.addEventListener("click", clickEventI);
    return () => {
      document.removeEventListener("click", clickEventI);
    };
  }, [showDialog]);

  return (
    <host shadowDom>
      <style>{style}</style>
      <div
        ref={ref}
        className="kun-fold-button"
      >
        <div
          onclick={(event) => onClick(event)}
          className={showDialog ? "kun-series-selected" : "kun-series-item"}
        >
          {kunTitle}
        </div>
        {
              showDialog && (
              <div className="fixed-right bg-white">
                <slot name="content" />
              </div>
              )
          }
      </div>
    </host>
  );
};

KunFoldButton.props = {
  kunTitle: {
    type: String,
    value: "kun-fold-button",
    reflect: true,
    event: {
      type: "changeMessage",
    },
  },
};

export default getComponentOrDefine("kun-fold-button", KunFoldButton);
