import { JSX } from "preact";
import { useEffect, useState } from "preact/hooks";
import Button from "../components/form/Button.tsx";

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={`fixed inset-0 bg-black/60 z-[8] flex items-center justify-center ${!visible ? "hidden" : ""}`}>
        <div className="bg-white border border-gray-200 rounded-lg w-[500px] max-w-[90%] max-h-[60%] relative text-base cursor-pointer">
          <i
            className="bi bi-x absolute right-4 top-3 text-2xl"
            onClick={() => {
              hideModal();
            }}
          />
          {title ? <div className="p-4 border-b border-gray-200 font-medium">{title}</div> : null}
          <div className="p-4">{content}</div>
          {actions.length > 0
            ? (
              <div className="flex justify-end border-t border-gray-200 p-4">
                {actions.map((action, index) => (
                  <Button
                    type="button"
                    key={index}
                    className="ml-2 first:ml-0"
                    onClick={() => {
                      action.onClick
                        ? action.onClick(action.text)
                        : hideModal();
                    }}
                  >
                    {action.text}
                  </Button>
                ))}
              </div>
            )
            : null}
        </div>
      </div>
    </>
  );
}
