#include "ui/theme.h"
#include "db/database.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static GtkCssProvider *css_provider = NULL;

void theme_init(void) {
  if (!css_provider) {
    css_provider = gtk_css_provider_new();
    GdkScreen *screen = gdk_screen_get_default();
    gtk_style_context_add_provider_for_screen(
        screen, GTK_STYLE_PROVIDER(css_provider),
        GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
  }
}

static void load_theme_file(const char *filename) {
  if (!filename)
    return;

  // Try finding the file in typical locations
  // 1. Local resources (dev mode relative to correct CWD)
  char path[512];
  snprintf(path, sizeof(path), "resources/themes/%s", filename);

  if (access(path, F_OK) != 0) {
    // 2. Try install path
    snprintf(path, sizeof(path), "/usr/share/leafweb/resources/themes/%s",
             filename);
  }

  if (access(path, F_OK) != 0) {
    // 3. Try relative to build/ (one level up if running from build)
    snprintf(path, sizeof(path), "../resources/themes/%s", filename);
  }

  // Attempt load if found or just try the name directly
  gtk_css_provider_load_from_path(css_provider, path, NULL);
}

void theme_apply(GtkWidget *window, Profile *profile) {
  theme_update(window, profile);
}

void theme_update(GtkWidget *window, Profile *profile) {
  if (!profile || !profile->db)
    return;

  char *theme = settings_get(profile->db, "theme");
  gboolean dark_mode = FALSE;
  const char *css_file = "default.css";

  if (theme) {
    if (g_strcmp0(theme, "Dark") == 0) {
      dark_mode = TRUE;
      css_file = "dark.css";
    } else if (g_strcmp0(theme, "Light") == 0) {
      css_file = "light.css";
    } else if (g_strcmp0(theme, "Liquid Glass") == 0) {
      css_file = "liquid-glass.css";
    } else if (g_strcmp0(theme, "Nord") == 0) {
      dark_mode = TRUE;
      css_file = "nord.css";
    } else if (g_strcmp0(theme, "Dracula") == 0) {
      dark_mode = TRUE;
      css_file = "dracula.css";
    } else if (g_strcmp0(theme, "Monokai") == 0) {
      dark_mode = TRUE;
      css_file = "monokai.css";
    } else if (g_strcmp0(theme, "System") == 0) {
      // Check system setting
      GtkSettings *settings = gtk_settings_get_default();
      gboolean prefer_dark;
      g_object_get(settings, "gtk-application-prefer-dark-theme", &prefer_dark,
                   NULL);
      dark_mode = prefer_dark;
    }
    g_free(theme);
  } else {
    // Default to System behavior if no setting
    GtkSettings *settings = gtk_settings_get_default();
    gboolean prefer_dark;
    g_object_get(settings, "gtk-application-prefer-dark-theme", &prefer_dark,
                 NULL);
    dark_mode = prefer_dark;
  }

  GtkSettings *settings = gtk_settings_get_default();
  g_object_set(settings, "gtk-application-prefer-dark-theme", dark_mode, NULL);

  load_theme_file(css_file);
}
