import * as ThemeController from "../controllers/theme-controller";
import { Config } from "../config/store";
import {
  showNoticeNotification,
  showSuccessNotification,
} from "../states/notifications";
import AnimatedModal from "../utils/animated-modal";
import { getTheme } from "../states/theme";

type State = {
  includeBackground: boolean;
};

const state: State = {
  includeBackground: false,
};

export function show(): void {
  void modal.show({
    beforeAnimation: async (m) => {
      m.qs<HTMLInputElement>("input[type='checkbox']")?.setChecked(false);
      state.includeBackground = false;
    },
  });
}

async function generateUrl(): Promise<string> {
  const newTheme: {
    c: string[]; //colors
    i?: string; //image
    s?: string; //size
    f?: object; //filter
  } = {
    c: ThemeController.convertThemeToCustomColors(getTheme()),
  };

  if (state.includeBackground) {
    newTheme.i = Config.customBackground;
    newTheme.s = Config.customBackgroundSize;
    newTheme.f = Config.customBackgroundFilter;
  }

  return (
    window.location.origin + "?customTheme=" + btoa(JSON.stringify(newTheme))
  );
}

async function copy(): Promise<void> {
  const url = await generateUrl();

  try {
    await navigator.clipboard.writeText(url);
    showSuccessNotification("URL Copied to clipboard");
    void modal.hide();
  } catch (e) {
    showNoticeNotification(
      "Looks like we couldn't copy the link straight to your clipboard. Please copy it manually.",
      {
        durationMs: 5000,
      },
    );
    void urlModal.show({
      modalChain: modal,
      focusFirstInput: "focusAndSelect",
      beforeAnimation: async (m) => {
        m.qs<HTMLInputElement>("input")?.setValue(url);
      },
    });
  }
}

const modal = new AnimatedModal({
  dialogId: "shareCustomThemeModal",
  setup: async (modalEl): Promise<void> => {
    modalEl.qs("button")?.on("click", copy);
    modalEl
      .qs<HTMLInputElement>("input[type='checkbox']")
      ?.on("change", (e) => {
        state.includeBackground = (e.target as HTMLInputElement).checked;
      });
  },
});

const urlModal = new AnimatedModal({
  dialogId: "shareCustomThemeUrlModal",
  customEscapeHandler: async (): Promise<void> => {
    await urlModal.hide({
      clearModalChain: true,
    });
  },
  customWrapperClickHandler: async (): Promise<void> => {
    await urlModal.hide({
      clearModalChain: true,
    });
  },
});
