#include "settings/settings_window.h"
#include "db/database.h"
#include "ui/theme.h"
#include <stdlib.h>
#include <string.h>

static GtkWidget *settings_window = NULL;
static Profile *current_profile = NULL;

// Helper to save string setting
static void save_string_setting(GtkWidget *widget, const char *key) {
  if (!current_profile || !current_profile->db)
    return;
  const char *value = gtk_entry_get_text(GTK_ENTRY(widget));
  settings_set(current_profile->db, key, value);
}

// Helper to save boolean setting (switch)
static void save_bool_setting(GtkWidget *widget, GParamSpec *pspec,
                              const char *key) {
  if (!current_profile || !current_profile->db)
    return;
  gboolean active = gtk_switch_get_active(GTK_SWITCH(widget));
  settings_set(current_profile->db, key, active ? "true" : "false");
}

// Helper to save int setting (spin button)
static void save_int_setting(GtkWidget *widget, const char *key) {
  if (!current_profile || !current_profile->db)
    return;
  int value = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(widget));
  char *str_val = g_strdup_printf("%d", value);
  settings_set(current_profile->db, key, str_val);
  g_free(str_val);
}

// Helper to save combo setting
static void save_combo_setting(GtkWidget *widget, const char *key) {
  if (!current_profile || !current_profile->db)
    return;
  const char *value =
      gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(widget));
  if (value) {
    settings_set(current_profile->db, key, value);
  }
}

// Helper to load string setting
static void load_string_setting(GtkWidget *widget, const char *key,
                                const char *default_val) {
  if (!current_profile || !current_profile->db)
    return;
  char *val = settings_get(current_profile->db, key);
  gtk_entry_set_text(GTK_ENTRY(widget), val ? val : default_val);
  if (val)
    g_free(val);
}

// Helper to load boolean setting
static void load_bool_setting(GtkWidget *widget, const char *key,
                              gboolean default_val) {
  if (!current_profile || !current_profile->db)
    return;
  char *val = settings_get(current_profile->db, key);
  gboolean active = default_val;
  if (val) {
    active = (g_strcmp0(val, "true") == 0);
    g_free(val);
  }
  gtk_switch_set_active(GTK_SWITCH(widget), active);
}

// Helper to load int setting
static void load_int_setting(GtkWidget *widget, const char *key,
                             int default_val) {
  if (!current_profile || !current_profile->db)
    return;
  char *val = settings_get(current_profile->db, key);
  int value = default_val;
  if (val) {
    value = atoi(val);
    g_free(val);
  }
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget), value);
}

// Helper to load combo setting
static void load_combo_setting(GtkWidget *widget, const char *key,
                               const char *default_val) {
  if (!current_profile || !current_profile->db)
    return;
  char *val = settings_get(current_profile->db, key);
  const char *target_val = val ? val : default_val;

  // Find and select the matching item in the combo box
  GtkComboBoxText *combo = GTK_COMBO_BOX_TEXT(widget);
  GtkTreeModel *model = gtk_combo_box_get_model(GTK_COMBO_BOX(combo));
  GtkTreeIter iter;
  gboolean valid = gtk_tree_model_get_iter_first(model, &iter);
  int index = 0;

  while (valid) {
    gchar *item_text = NULL;
    gtk_tree_model_get(model, &iter, 0, &item_text, -1);
    if (item_text && g_strcmp0(item_text, target_val) == 0) {
      gtk_combo_box_set_active(GTK_COMBO_BOX(combo), index);
      g_free(item_text);
      break;
    }
    g_free(item_text);
    valid = gtk_tree_model_iter_next(model, &iter);
    index++;
  }

  if (val)
    g_free(val);
}

// Callback for theme changes to apply immediately
static void on_theme_changed(GtkWidget *widget, const char *key) {
  if (!current_profile || !current_profile->db)
    return;

  // 1. Save setting
  save_combo_setting(widget, key);

  // 2. Apply theme immediately
  theme_update(settings_window, current_profile);
}

static GtkWidget *create_page_appearance(void) {
  GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);

  // Theme
  GtkWidget *row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("Theme"), FALSE, FALSE, 0);
  GtkWidget *theme_combo = gtk_combo_box_text_new();
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(theme_combo), "Light");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(theme_combo), "Dark");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(theme_combo),
                                 "Liquid Glass");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(theme_combo), "Nord");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(theme_combo), "Dracula");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(theme_combo), "Monokai");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(theme_combo), "System");

  // Load saved specific setting
  load_combo_setting(theme_combo, "theme", "System");

  gtk_box_pack_end(GTK_BOX(row), theme_combo, FALSE, FALSE, 0);
  // ...
  g_signal_connect(theme_combo, "changed", G_CALLBACK(on_theme_changed),
                   "theme");

  // Accent Color
  row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("Accent Color"), FALSE, FALSE,
                     0);
  GtkWidget *color_btn = gtk_color_button_new();
  gtk_box_pack_end(GTK_BOX(row), color_btn, FALSE, FALSE, 0);
  // Saving color is complex (GdkRGBA to string), skipping for brevity

  return box;
}

static GtkWidget *create_page_home(void) {
  GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);

  // Home Page
  GtkWidget *row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("Home Page"), FALSE, FALSE, 0);
  GtkWidget *entry = gtk_entry_new();
  load_string_setting(entry, "home_page", "https://google.com");
  gtk_box_pack_end(GTK_BOX(row), entry, TRUE, TRUE, 0);
  g_signal_connect(entry, "changed", G_CALLBACK(save_string_setting),
                   "home_page");

  // Search Engine
  row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("Search Engine"), FALSE, FALSE,
                     0);
  GtkWidget *search_combo = gtk_combo_box_text_new();
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(search_combo), "Google");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(search_combo),
                                 "DuckDuckGo");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(search_combo), "Bing");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(search_combo),
                                 "Brave Search");
  load_combo_setting(search_combo, "search_engine", "Google");
  gtk_box_pack_end(GTK_BOX(row), search_combo, FALSE, FALSE, 0);
  g_signal_connect(search_combo, "changed", G_CALLBACK(save_combo_setting),
                   "search_engine");

  return box;
}

static GtkWidget *create_page_privacy(void) {
  GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);

  // HTTPS Only
  GtkWidget *row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("HTTPS Only Mode"), FALSE,
                     FALSE, 0);
  GtkWidget *sw = gtk_switch_new();
  load_bool_setting(sw, "https_only", FALSE);
  gtk_box_pack_end(GTK_BOX(row), sw, FALSE, FALSE, 0);
  g_signal_connect(sw, "notify::active", G_CALLBACK(save_bool_setting),
                   "https_only");

  // Block Popups
  row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("Block Pop-ups"), FALSE, FALSE,
                     0);
  sw = gtk_switch_new();
  load_bool_setting(sw, "block_popups", TRUE);
  gtk_box_pack_end(GTK_BOX(row), sw, FALSE, FALSE, 0);
  g_signal_connect(sw, "notify::active", G_CALLBACK(save_bool_setting),
                   "block_popups");

  return box;
}

static GtkWidget *create_page_downloads(void) {
  GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);

  // Download Path
  GtkWidget *row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("Download Path"), FALSE, FALSE,
                     0);
  GtkWidget *chooser = gtk_file_chooser_button_new(
      "Select Download Folder", GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
  // Loading/Saving path logic here...
  gtk_box_pack_end(GTK_BOX(row), chooser, TRUE, TRUE, 0);

  // Multipart
  row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("Multipart Connections"),
                     FALSE, FALSE, 0);
  GtkWidget *spin = gtk_spin_button_new_with_range(1, 32, 1);
  load_int_setting(spin, "multipart_parts", 4);
  gtk_box_pack_end(GTK_BOX(row), spin, FALSE, FALSE, 0);
  g_signal_connect(spin, "value-changed", G_CALLBACK(save_int_setting),
                   "multipart_parts");

  return box;
}

static GtkWidget *create_page_extensions(void) {
  GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);

  // DarkReader
  GtkWidget *row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("DarkReader"), FALSE, FALSE,
                     0);
  GtkWidget *sw = gtk_switch_new();
  load_bool_setting(sw, "ext_darkreader", FALSE);
  gtk_box_pack_end(GTK_BOX(row), sw, FALSE, FALSE, 0);
  g_signal_connect(sw, "notify::active", G_CALLBACK(save_bool_setting),
                   "ext_darkreader");

  // AdBlock
  row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("AdBlock"), FALSE, FALSE, 0);
  sw = gtk_switch_new();
  load_bool_setting(sw, "ext_adblock", TRUE);
  gtk_box_pack_end(GTK_BOX(row), sw, FALSE, FALSE, 0);
  g_signal_connect(sw, "notify::active", G_CALLBACK(save_bool_setting),
                   "ext_adblock");

  // SponsorBlock
  row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("SponsorBlock"), FALSE, FALSE,
                     0);
  sw = gtk_switch_new();
  load_bool_setting(sw, "ext_sponsorblock", FALSE);
  gtk_box_pack_end(GTK_BOX(row), sw, FALSE, FALSE, 0);
  g_signal_connect(sw, "notify::active", G_CALLBACK(save_bool_setting),
                   "ext_sponsorblock");

  return box;
}

static GtkWidget *create_page_system(void) {
  GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);

  // Hardware Acceleration
  GtkWidget *row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
  gtk_box_pack_start(GTK_BOX(box), row, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(row), gtk_label_new("Hardware Acceleration"),
                     FALSE, FALSE, 0);
  GtkWidget *hw_accel_combo = gtk_combo_box_text_new();
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(hw_accel_combo), "Always");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(hw_accel_combo),
                                 "On Demand");
  gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(hw_accel_combo), "Never");
  load_combo_setting(hw_accel_combo, "hardware_acceleration", "On Demand");
  gtk_box_pack_end(GTK_BOX(row), hw_accel_combo, FALSE, FALSE, 0);
  g_signal_connect(hw_accel_combo, "changed", G_CALLBACK(save_combo_setting),
                   "hardware_acceleration");

  return box;
}

static GtkWidget *create_page_about(void) {
  GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 20);
  gtk_widget_set_halign(box, GTK_ALIGN_CENTER);
  gtk_widget_set_valign(box, GTK_ALIGN_CENTER);

  GtkWidget *label = gtk_label_new(NULL);
  gtk_label_set_markup(GTK_LABEL(label),
                       "<span size='xx-large' weight='bold'>Leaf Web</span>");
  gtk_box_pack_start(GTK_BOX(box), label, FALSE, FALSE, 0);

  label = gtk_label_new("Version 1.0.0");
  gtk_box_pack_start(GTK_BOX(box), label, FALSE, FALSE, 0);

  // Leaf animation placeholder
  label = gtk_label_new("🍂"); // Simple emoji for now
  gtk_box_pack_start(GTK_BOX(box), label, FALSE, FALSE, 0);

  return box;
}

static void on_sidebar_row_selected(GtkListBox *box, GtkListBoxRow *row,
                                    GtkStack *stack) {
  if (!row)
    return;
  int index = gtk_list_box_row_get_index(row);
  char name[32];
  sprintf(name, "page%d", index);
  gtk_stack_set_visible_child_name(stack, name);
}

void settings_window_show(GtkWindow *parent, Profile *profile) {
  if (settings_window) {
    gtk_window_present(GTK_WINDOW(settings_window));
    return;
  }

  current_profile = profile;

  settings_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_transient_for(GTK_WINDOW(settings_window), parent);
  gtk_window_set_title(GTK_WINDOW(settings_window), "Settings");
  gtk_window_set_default_size(GTK_WINDOW(settings_window), 800, 600);

  GtkWidget *paned = gtk_paned_new(GTK_ORIENTATION_HORIZONTAL);
  gtk_container_add(GTK_CONTAINER(settings_window), paned);

  // Sidebar
  GtkWidget *sidebar = gtk_list_box_new();
  gtk_widget_set_size_request(sidebar, 200, -1);
  gtk_paned_pack1(GTK_PANED(paned), sidebar, FALSE, FALSE);

  const char *categories[] = {"Appearance", "Home & Search", "Privacy",
                              "Downloads",  "Extensions",    "Profiles",
                              "System",     "About",         NULL};

  for (int i = 0; categories[i] != NULL; i++) {
    GtkWidget *label = gtk_label_new(categories[i]);
    gtk_widget_set_halign(label, GTK_ALIGN_START);
    gtk_widget_set_margin_start(label, 10);
    gtk_widget_set_margin_top(label, 10);
    gtk_widget_set_margin_bottom(label, 10);
    gtk_list_box_insert(GTK_LIST_BOX(sidebar), label, -1);
  }

  // Pages Stack
  GtkWidget *stack = gtk_stack_new();
  gtk_paned_pack2(GTK_PANED(paned), stack, TRUE, FALSE);

  gtk_stack_add_named(GTK_STACK(stack), create_page_appearance(), "page0");
  gtk_stack_add_named(GTK_STACK(stack), create_page_home(), "page1");
  gtk_stack_add_named(GTK_STACK(stack), create_page_privacy(), "page2");
  gtk_stack_add_named(GTK_STACK(stack), create_page_downloads(), "page3");
  gtk_stack_add_named(GTK_STACK(stack), create_page_extensions(), "page4");
  gtk_stack_add_named(GTK_STACK(stack),
                      gtk_label_new("Profiles Management (TODO)"), "page5");
  gtk_stack_add_named(GTK_STACK(stack), create_page_system(), "page6");
  gtk_stack_add_named(GTK_STACK(stack), create_page_about(), "page7");

  g_signal_connect(sidebar, "row-selected", G_CALLBACK(on_sidebar_row_selected),
                   stack);
  g_signal_connect(settings_window, "destroy", G_CALLBACK(gtk_widget_destroyed),
                   &settings_window);

  gtk_widget_show_all(settings_window);
}
