#include "ui/window.h"
#include "downloads/download_manager.h"
#include "downloads/download_window.h"
#include "ui/headerbar.h"
#include "ui/menu.h"
#include "ui/tabs.h"
#include "ui/theme.h"
#include "ui/toolbar.h"
#include <gdk/gdkkeysyms.h>
#include <webkit2/webkit2.h>

static void on_download_started(WebKitWebContext *context,
                                WebKitDownload *download, gpointer user_data) {
  // Use download_start_webkit directly as wrapper doesn't exist
  download_start_webkit(download, 4);
  download_window_show();
}

// Zoom action callbacks for AccelGroup
static gboolean on_zoom_in_accel(GtkAccelGroup *group, GObject *acceleratable,
                                 guint keyval, GdkModifierType modifier,
                                 gpointer user_data) {
  TabManager *manager = (TabManager *)user_data;
  WebKitWebView *view = tab_manager_get_current_webview(manager);
  if (view) {
    double zoom = webkit_web_view_get_zoom_level(view);
    webkit_web_view_set_zoom_level(view, zoom + 0.1);
    g_print("Zoom In: %.2f\n", zoom + 0.1);
  }
  return TRUE;
}

static gboolean on_zoom_out_accel(GtkAccelGroup *group, GObject *acceleratable,
                                  guint keyval, GdkModifierType modifier,
                                  gpointer user_data) {
  TabManager *manager = (TabManager *)user_data;
  WebKitWebView *view = tab_manager_get_current_webview(manager);
  if (view) {
    double zoom = webkit_web_view_get_zoom_level(view);
    webkit_web_view_set_zoom_level(view, zoom - 0.1);
    g_print("Zoom Out: %.2f\n", zoom - 0.1);
  }
  return TRUE;
}

static gboolean on_window_key_press(GtkWidget *widget, GdkEventKey *event,
                                    gpointer user_data) {
  TabManager *manager = (TabManager *)user_data;
  guint state = event->state & gtk_accelerator_get_default_mod_mask();

  // Debug print with flush
  // g_print("Debug: Key pressed keyval=%d, state=%u\n", event->keyval, state);

  if (state == GDK_CONTROL_MASK) {
    switch (event->keyval) {
      // Zoom moved to AccelGroup
    case GDK_KEY_t:
    case GDK_KEY_T:
      tab_manager_new_tab(manager, NULL);
      return TRUE;
    case GDK_KEY_w:
    case GDK_KEY_W:
      tab_manager_close_current(manager);
      return TRUE;
    case GDK_KEY_r:
    case GDK_KEY_R:
      tab_manager_reload_current(manager);
      return TRUE;
    case GDK_KEY_Tab:
    case GDK_KEY_Page_Down:
      tab_manager_next_tab(manager);
      return TRUE;
    }
  } else if (state == (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) {
    switch (event->keyval) {
    case GDK_KEY_t:
    case GDK_KEY_T:
      tab_manager_reopen_last_tab(manager);
      return TRUE;
    case GDK_KEY_Tab:
    case GDK_KEY_ISO_Left_Tab:
    case GDK_KEY_Page_Up:
      tab_manager_prev_tab(manager);
      return TRUE;
    }
  } else if (state == GDK_MOD1_MASK) { // Alt
    switch (event->keyval) {
    case GDK_KEY_Left: {
      WebKitWebView *view = tab_manager_get_current_webview(manager);
      if (view && webkit_web_view_can_go_back(view)) {
        webkit_web_view_go_back(view);
      }
    }
      return TRUE;
    case GDK_KEY_Right: {
      WebKitWebView *view = tab_manager_get_current_webview(manager);
      if (view && webkit_web_view_can_go_forward(view)) {
        webkit_web_view_go_forward(view);
      }
    }
      return TRUE;
    }
  } else if (state == 0) {
    if (event->keyval == GDK_KEY_F5) {
      tab_manager_reload_current(manager);
      return TRUE;
    }
  }

  return FALSE;
}

void create_window(GtkApplication *app, Profile *profile) {
  g_print("create_window called\n");
  GtkWidget *window = gtk_application_window_new(app);
  gtk_style_context_add_class(gtk_widget_get_style_context(window),
                              "browser-root");
  gtk_window_set_default_size(GTK_WINDOW(window), 1024, 768);

  // Initialize Theme
  g_print("Initializing theme...\n");
  theme_init();
  theme_apply(window, profile);

  // Tab Manager
  g_print("Creating TabManager...\n");
  TabManager *tab_manager = tab_manager_new(GTK_WINDOW(window), profile);

  // Header Bar (Titlebar + Tabs)
  g_print("Creating HeaderBar...\n");
  GtkWidget *header_bar =
      create_headerbar(tab_manager_get_header_widget(tab_manager));
  gtk_window_set_titlebar(GTK_WINDOW(window), header_bar);

  // Keyboard Shortcuts (Standard)
  g_signal_connect(window, "key-press-event", G_CALLBACK(on_window_key_press),
                   tab_manager);

  // Accelerators for Zoom (Robust)
  GtkAccelGroup *accel_group = gtk_accel_group_new();
  gtk_window_add_accel_group(GTK_WINDOW(window), accel_group);

  GClosure *zoom_in_closure =
      g_cclosure_new(G_CALLBACK(on_zoom_in_accel), tab_manager, NULL);
  GClosure *zoom_out_closure =
      g_cclosure_new(G_CALLBACK(on_zoom_out_accel), tab_manager, NULL);

  // Ctrl+=
  gtk_accel_group_connect(accel_group, GDK_KEY_equal, GDK_CONTROL_MASK,
                          GTK_ACCEL_VISIBLE, zoom_in_closure);
  // Ctrl++ (Shift+= usually)
  gtk_accel_group_connect(accel_group, GDK_KEY_plus, GDK_CONTROL_MASK,
                          GTK_ACCEL_VISIBLE, zoom_in_closure);
  // Ctrl+Numpad+
  gtk_accel_group_connect(accel_group, GDK_KEY_KP_Add, GDK_CONTROL_MASK,
                          GTK_ACCEL_VISIBLE, zoom_in_closure);

  // Ctrl+-
  gtk_accel_group_connect(accel_group, GDK_KEY_minus, GDK_CONTROL_MASK,
                          GTK_ACCEL_VISIBLE, zoom_out_closure);
  // Ctrl+Numpad-
  gtk_accel_group_connect(accel_group, GDK_KEY_KP_Subtract, GDK_CONTROL_MASK,
                          GTK_ACCEL_VISIBLE, zoom_out_closure);

  // Main Content Box
  GtkWidget *main_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
  gtk_container_add(GTK_CONTAINER(window), main_box);

  // Toolbar
  g_print("Creating Toolbar...\n");
  GtkEntry *url_entry = NULL;
  GtkWidget *toolbar = create_toolbar(tab_manager, profile, &url_entry);
  gtk_box_pack_start(GTK_BOX(main_box), toolbar, FALSE, FALSE, 0);

  // Connect URL entry to tab manager
  if (url_entry) {
    tab_manager_set_url_entry(tab_manager, url_entry);
  }

  // Connect menu button in toolbar
  g_print("Connecting menu...\n");
  GList *children = gtk_container_get_children(GTK_CONTAINER(toolbar));
  for (GList *iter = children; iter != NULL; iter = iter->next) {
    GtkWidget *child = GTK_WIDGET(iter->data);
    // Use strict check for menu button
    if (g_object_get_data(G_OBJECT(child), "is_menu_button") != NULL &&
        g_object_get_data(G_OBJECT(child), "profile") == profile) {
      // This is the menu button
      menu_attach(child, tab_manager, GTK_WINDOW(window), profile);
    }
  }
  g_list_free(children);

  // Tab Content
  g_print("Adding tab content...\n");
  GtkWidget *content = tab_manager_get_content_widget(tab_manager);
  gtk_box_pack_start(GTK_BOX(main_box), content, TRUE, TRUE, 0);

  // Create first tab
  g_print("Creating first tab...\n");
  tab_manager_new_tab(tab_manager, NULL);

  // Connect download signal (global)
  if (profile->context) {
    g_signal_connect(webkit_web_context_get_default(), "download-started",
                     G_CALLBACK(on_download_started), NULL);
  }

  // Don't manually handle destroy with gtk_main_quit - GtkApplication handles
  // this g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit),
  // NULL);

  g_print("Showing window...\n");
  gtk_widget_show_all(window);
}
