import { listen } from "@tauri-apps/api/event";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { setWindowTheme } from "@yaakapp-internal/mac-window";
import type { ModelPayload } from "@yaakapp-internal/models";
import type { Appearance } from "@yaakapp-internal/theme";
import {
  applyThemeToDocument,
  getCSSAppearance,
  subscribeToPreferredAppearance,
} from "@yaakapp-internal/theme";
import { getSettings } from "./lib/settings";
import { getResolvedTheme } from "./lib/themes";

// NOTE: CSS appearance isn't as accurate as getting it async from the window (next step), but we want
//  a good appearance guess so we're not waiting too long
let preferredAppearance: Appearance = getCSSAppearance();
subscribeToPreferredAppearance(async (a) => {
  preferredAppearance = a;
  await configureTheme();
});

configureTheme().then(
  async () => {
    // To prevent theme flashing, the backend hides new windows by default, so we
    // need to show it here, after configuring the theme for the first time.
    await getCurrentWebviewWindow().show();
  },
  (err) => console.log("Failed to configure theme", err),
);

// Listen for settings changes, the re-compute theme
listen<ModelPayload>("model_write", async (event) => {
  if (event.payload.change.type !== "upsert") return;

  const model = event.payload.model.model;
  if (model !== "settings" && model !== "plugin") return;
  await configureTheme();
}).catch(console.error);

async function configureTheme() {
  const settings = await getSettings();
  const theme = await getResolvedTheme(
    preferredAppearance,
    settings.appearance,
    settings.themeLight,
    settings.themeDark,
  );
  applyThemeToDocument(theme.active);
  if (theme.active.base.surface != null) {
    setWindowTheme(theme.active.base.surface);
  }
}
