import { useEffect, useState } from "preact/hooks";
import { EditorMode } from "./Editor.tsx";

interface TopBarProps {
  allowMode: EditorMode;
  isLogined: boolean;
  shared: boolean;
  title: string;
  id: string;
}

const settingsData: { [key: string]: string } = {};
const shareData: { [key: string]: boolean } = {};

export default function TopBar(props: TopBarProps) {
  const [mode, setMode] = useState(props.allowMode);

  const doLogout = async () => {
    const resp = await fetch("/api/user/logout");
    const respJson = await resp.json();
    if (respJson.success) {
      location.href = "/login";
      return true;
    }
    return false;
  };

  const goHome = () => {
    location.href = "/";
  };

  const showShare = () => {
    shareData["shared"] = shareData["submittedShared"] !== undefined
      ? shareData["submittedShared"]
      : props.shared;
    window.$modal?.show(
      "Share options",
      <div style="display: flex; align-items: center">
        <input
          type="checkbox"
          checked={shareData["shared"]}
          onChange={(e) => {
            shareData["shared"] = (e.target as HTMLInputElement).checked;
            (
              document.querySelector("#shared-button") as HTMLButtonElement
            ).style.visibility = shareData["shared"] ? "visible" : "hidden";
          }}
        />
        <span style="margin: 0 8px">Shared to friends</span>
        <button
          id="shared-button"
          style={`${!shareData["shared"] ? ";visibility: hidden" : ""}`}
          onClick={async () => {
            await navigator.clipboard.writeText(location.href.split("?")[0]);
          }}
        >
          Copy Link
        </button>
      </div>,
      [
        {
          text: "Confirm",
          onClick: async () => {
            const resp = await fetch("/api/share", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                id: props.id,
                shared: shareData["shared"],
              }),
            });
            const respJson = await resp.json();
            if (respJson.success) {
              shareData["submittedShared"] = shareData["shared"];
              window.$modal?.hide();
            }
          },
        },
      ],
    );
  };

  const showSetting = () => {
    settingsData["title"] = settingsData["submittedTitle"] || props.title;
    window.$modal?.show(
      "Post Settings",
      <div style="display: flex; align-items: center">
        <span style="margin-right: 8px">Title</span>
        <input
          placeholder="Post title here"
          value={settingsData["title"]}
          onInput={(e) => {
            settingsData["title"] = (e.target as HTMLInputElement).value;
          }}
        />
      </div>,
      [
        {
          text: "Confirm",
          onClick: async () => {
            const resp = await fetch("/api/post", {
              method: "PUT",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                id: props.id,
                title: settingsData["title"],
              }),
            });
            const respJson = await resp.json();
            if (respJson.success) {
              settingsData["submittedTitle"] = settingsData["title"];
              document.title = settingsData["title"];
              window.$modal?.hide();
            }
          },
        },
      ],
    );
  };

  // Event listener
  const modeChangeListener = (e: CustomEvent) => {
    if (
      e.detail &&
      (props.allowMode === e.detail || props.allowMode === EditorMode.Both)
    ) {
      setMode(e.detail);
    }
  };

  // Event dispatcher
  const modeChangeDispatcher = (mode: EditorMode) => {
    dispatchEvent(new CustomEvent("ModeChange", { detail: mode }));
  };

  // Init event listeners
  useEffect(() => {
    addEventListener("ModeChange", modeChangeListener);

    return () => {
      removeEventListener("ModeChange", modeChangeListener);
    };
  }, []);

  return (
    <div className="pd-top-bar">
      <div
        className={`pd-top-bar-mode-switcher${
          mode !== EditorMode.Both ? " hidden" : ""
        }`}
      >
        <button
          className={`pd-top-bar-btn${
            mode === EditorMode.Edit ? " active" : ""
          }`}
          id="edit"
          type="button"
          onClick={() => {
            modeChangeDispatcher(EditorMode.Edit);
          }}
        >
          Edit
        </button>
        <button
          className={`pd-top-bar-btn${
            mode === EditorMode.Read ? " active" : ""
          }`}
          id="read"
          type="button"
          onClick={() => {
            modeChangeDispatcher(EditorMode.Read);
          }}
        >
          Read
        </button>
        <button
          className={`pd-top-bar-btn${
            mode === EditorMode.Both ? " active" : ""
          }`}
          id="both"
          type="button"
          onClick={() => {
            modeChangeDispatcher(EditorMode.Both);
          }}
        >
          Both
        </button>
      </div>
      {!props.isLogined
        ? <span className="pd-top-bar-title">{props.title}</span>
        : null}
      {props.isLogined
        ? (
          <div className="pd-top-bar-tool-icons">
            <i className="bi bi-box-arrow-left" onClick={doLogout} />
            <i className="bi bi-house-door" onClick={goHome} />
            <i className="bi bi-share" onClick={showShare} />
            <i className="bi bi-gear" onClick={showSetting} />
          </div>
        )
        : null}
    </div>
  );
}
