import { JSX } from "preact";
import { useEffect, useState } from "preact/hooks";

interface ModalAction {
  text: string;
  onClick?: (text: string) => void | Promise<void>;
}

interface ModalGlobalHook {
  show: (
    title: string,
    content: string | JSX.Element,
    actions: ModalAction[],
  ) => void;
  hide: () => void;
}

declare global {
  var $modal: ModalGlobalHook | undefined;
}

export default function Modal() {
  const [visible, setVisible] = useState(false);
  const [title, setTitle] = useState("");
  const [content, setContent] = useState<string | JSX.Element>("");
  const [actions, setActions] = useState<ModalAction[]>([]);

  const showModal = (
    newTitle: string,
    newContent: string | JSX.Element,
    newActions: ModalAction[],
  ) => {
    setTitle(newTitle || "");
    setContent(newContent || "");
    setActions(newActions || []);
    setVisible(true);
  };

  const hideModal = () => {
    setVisible(false);
  };

  useEffect(() => {
    globalThis.$modal = {
      show: (
        title: string,
        content: string | JSX.Element,
        actions: ModalAction[],
      ) => showModal(title, content, actions),
      hide: () => hideModal(),
    };

    return () => {
      delete globalThis.$modal;
    };
  }, []);

  return (
    <>
      <div className={`pd-modal${!visible ? " pd-modal-hidden" : ""}`}>
        <div className="pd-modal-content">
          <i
            className="bi bi-x pd-modal-close"
            onClick={() => {
              hideModal();
            }}
          />
          {title ? <div className="pd-modal-title">{title}</div> : null}
          <div className="pd-modal-body">{content}</div>
          {actions.length > 0
            ? (
              <div className="pd-modal-footer">
                {actions.map((action, index) => (
                  <button
                    type="button"
                    key={index}
                    onClick={() => {
                      action.onClick
                        ? action.onClick(action.text)
                        : hideModal();
                    }}
                  >
                    {action.text}
                  </button>
                ))}
              </div>
            )
            : null}
        </div>
      </div>
    </>
  );
}
