import { useEffect, useState } from "preact/hooks";
import { EditorMode } from "./Editor.tsx";
import Button from "../components/form/Button.tsx";
import Input from "../components/form/Input.tsx";
import Checkbox from "../components/form/Checkbox.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;
    globalThis.$modal?.show(
      "Share options",
      <div style="display: flex; align-items: center">
        <Checkbox
          label="Share to friends"
          checked={shareData["shared"]}
          onChange={(e) => {
            shareData["shared"] = (e.target as HTMLInputElement).checked;
            (
              document.querySelector("#shared-button") as HTMLButtonElement
            ).style.visibility = shareData["shared"] ? "visible" : "hidden";
          }}
        />
        <Button
          type="button"
          id="shared-button"
          className="ml-2"
          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"];
              globalThis.$modal?.hide();
            }
          },
        },
      ],
    );
  };

  const showSetting = () => {
    settingsData["title"] = settingsData["submittedTitle"] || props.title;
    globalThis.$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"];
              globalThis.$modal?.hide();
            }
          },
        },
      ],
    );
  };

  // Event listener
  const modeChangeListener = (e: Event) => {
    const { detail } = e as CustomEvent;
    if (
      detail &&
      (props.allowMode === detail || props.allowMode === EditorMode.Both)
    ) {
      setMode(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="w-full flex mb-3 justify-between box-border flex-shrink-0">
      <div
        className={`border border-gray-300 rounded box-border text-sm ${
          props.allowMode !== EditorMode.Both ? "hidden" : ""
        }`}
      >
        <Button
          variant={mode === EditorMode.Edit ? "primary" : "default"}
          className="rounded-tr-none rounded-br-none"
          id="edit"
          type="button"
          onClick={() => {
            modeChangeDispatcher(EditorMode.Edit);
          }}
        >
          Edit
        </Button>
        <Button
          variant={mode === EditorMode.Read ? "primary" : "default"}
          className="rounded-none"
          id="read"
          type="button"
          onClick={() => {
            modeChangeDispatcher(EditorMode.Read);
          }}
        >
          Read
        </Button>
        <Button
          variant={mode === EditorMode.Both ? "primary" : "default"}
          className="rounded-tl-none rounded-bl-none"
          id="both"
          type="button"
          onClick={() => {
            modeChangeDispatcher(EditorMode.Both);
          }}
        >
          Both
        </Button>
      </div>
      {!props.isLogined
        ? (
          <span className="leading-[30px] text-2xl font-medium text-center w-full">
            {props.title}
          </span>
        )
        : null}
      {props.isLogined
        ? (
          <div className="h-[30px] leading-[28px] box-border px-2 border border-gray-300 rounded">
            <i
              className="bi bi-box-arrow-left mr-4 text-base cursor-pointer h-4 w-4 hover:text-blue-600"
              onClick={doLogout}
            />
            <i
              className="bi bi-house-door mr-4 text-base cursor-pointer h-4 w-4 hover:text-blue-600"
              onClick={goHome}
            />
            <i
              className="bi bi-share mr-4 text-base cursor-pointer h-4 w-4 hover:text-blue-600"
              onClick={showShare}
            />
            <i
              className="bi bi-gear text-base cursor-pointer h-4 w-4 hover:text-blue-600"
              onClick={showSetting}
            />
          </div>
        )
        : null}
    </div>
  );
}
