import { computed, reactive, watch } from "vue";
import { useRoute } from "vue-router";
import { defaultMenuMode } from "../../config/design";
import { getActiveTopLevelParent } from "./menu";
import { useNavigation } from "../../composables/useNavigation";
import { useSubSidebarContext } from "./context";

// Default visual settings for the app theme / layout.
// These are the values you see when you first load the app,
// before changing anything in the Settings panel.
export const layoutConfig = reactive({
  // Preset shown under "Presets"
  preset: "Aura",
  // Color selected under "Primary"
  // (use one of the names from AppConfig.primaryColors)
  primary: "sky",
  // Surface palette (see AppConfig.surfaces). When null, the UI
  // uses the default based on light/dark mode – in the Settings
  // screenshot this corresponds to the first "slate" option.
  surface: null,
  // "Color Scheme" -> Auto-syncs with browser/system preference
  darkTheme: false,
  // "Menu Type" – from design.js (maestro = our drawer + vertical submenu)
  menuMode: defaultMenuMode,
  // "Menu Theme" – light, dark, or primary
  menuTheme: "primary",
  // "Card Style" – Transparent or Filled
  cardStyle: "transparent",
});

// System preference media query listener
let systemPreferenceListener = null;
let isListenerSetup = false;

/**
 * Detects browser/system color scheme preference
 * @returns {boolean} true if system prefers dark mode, false otherwise
 */
function getSystemPreference() {
  if (typeof window === "undefined") return false;
  return (
    window.matchMedia &&
    window.matchMedia("(prefers-color-scheme: dark)").matches
  );
}

/**
 * Syncs darkTheme with browser/system preference
 * Called automatically on app startup and when system preference changes
 */
export function syncDarkThemeFromSystem() {
  const prefersDark = getSystemPreference();
  layoutConfig.darkTheme = prefersDark;

  // Update DOM class immediately
  if (prefersDark) {
    document.documentElement.classList.add("app-dark");
  } else {
    document.documentElement.classList.remove("app-dark");
  }
}

/**
 * Sets up listener for system preference changes
 * Automatically updates theme when user changes OS/browser dark mode setting
 * Only sets up once to prevent duplicate listeners
 */
function setupSystemPreferenceListener() {
  if (isListenerSetup || typeof window === "undefined" || !window.matchMedia)
    return;

  const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");

  // Initial sync
  syncDarkThemeFromSystem();

  // Listen for changes
  systemPreferenceListener = (e) => {
    syncDarkThemeFromSystem();
  };

  // Modern browsers
  if (mediaQuery.addEventListener) {
    mediaQuery.addEventListener("change", systemPreferenceListener);
  } else {
    // Fallback for older browsers
    mediaQuery.addListener(systemPreferenceListener);
  }

  isListenerSetup = true;
}

/**
 * Removes system preference listener
 */
// function removeSystemPreferenceListener() {
//     if (!systemPreferenceListener || !isListenerSetup) return;
//     if (typeof window === 'undefined' || !window.matchMedia) return;

//     const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

//     if (mediaQuery.removeEventListener) {
//         mediaQuery.removeEventListener('change', systemPreferenceListener);
//     } else {
//         mediaQuery.removeListener(systemPreferenceListener);
//     }

//     systemPreferenceListener = null;
//     isListenerSetup = false;
// }

// Initialize system preference sync on module load
// This ensures the app automatically follows browser/system dark mode preference
if (typeof window !== "undefined") {
  setupSystemPreferenceListener();
}

const layoutState = reactive({
  staticMenuInactive: false,
  overlayMenuActive: false,
  rightMenuVisible: false,
  configSidebarVisible: false,
  mobileMenuActive: false,
  searchBarActive: false,
  sidebarExpanded: true,
  menuHoverActive: false,
  activePath: null,
  anchored: false,
  // Submenu context: can come from context-config (priority) or route-based detection (fallback)
  // Format: { items: Array, parentPath: string } | null
  activeSubmenuContext: null,
  // Enable/disable route-based fallback for backward compatibility
  // Set to false to use only context-config system
  enableRouteBasedSubmenu: true,
});

export function useLayout() {
  const route = useRoute();
  const { activeContext, hasActiveContext } = useSubSidebarContext();
  const { menu } = useNavigation();

  const toggleMenu = () => {
    if (isDesktop()) {
      if (layoutConfig.menuMode === "static") {
        layoutState.staticMenuInactive = !layoutState.staticMenuInactive;
      }

      if (layoutConfig.menuMode === "overlay") {
        layoutState.overlayMenuActive = !layoutState.overlayMenuActive;
      }
    } else {
      layoutState.mobileMenuActive = !layoutState.mobileMenuActive;
    }
  };

  const toggleConfigSidebar = () => {
    layoutState.configSidebarVisible = !layoutState.configSidebarVisible;
  };

  const hideMobileMenu = () => {
    layoutState.mobileMenuActive = false;
  };

  const changeMenuMode = (menuMode) => {
    layoutConfig.menuMode = menuMode;
    layoutState.staticMenuInactive = false;
    layoutState.overlayMenuActive = false;
    layoutState.mobileMenuActive = false;
    layoutState.sidebarExpanded = false;
    layoutState.menuHoverActive = false;
    layoutState.anchored = false;

    if (isDesktop()) {
      if (menuMode === "maestro" || menuMode === "drawer") {
        // Sync route or context-config
        if (hasActiveContext.value) {
          // Context-config active: update sidebar state based on context
          const ctx = activeContext.value;
          if (ctx) {
            layoutState.activePath = ctx.parentPath || null;
            layoutState.sidebarExpanded = false;
          } else {
            layoutState.activePath = null;
            layoutState.sidebarExpanded = true;
          }
        } else {
          // Fallback to route-based
          syncRouteToLayout(route?.path);
        }
      } else {
        layoutState.activeSubmenuContext = null;
        layoutState.activePath = hasOverlaySubmenu.value ? null : route?.path;
      }
    }
  };

  const isDarkTheme = computed(() => layoutConfig.darkTheme);
  const isDesktop = () => window.innerWidth > 991;
  const isHorizontal = computed(() => layoutConfig.menuMode === "horizontal");
  const isCompact = computed(() => layoutConfig.menuMode === "compact");
  const isSlim = computed(() => layoutConfig.menuMode === "slim");

  const hasOverlaySubmenu = computed(
    () =>
      layoutConfig.menuMode === "slim" ||
      layoutConfig.menuMode === "compact" ||
      layoutConfig.menuMode === "horizontal",
  );
  const hasOpenOverlaySubmenu = computed(
    () =>
      hasOverlaySubmenu.value &&
      layoutState.activePath !== null &&
      layoutState.activePath !== "/",
  );
  const hasOpenOverlay = computed(
    () => layoutState.overlayMenuActive || hasOpenOverlaySubmenu.value,
  );

  /**
   * Get active submenu items: context-config (if used), then route-based from backend tree (Settings, Companies).
   */
  const activeSubitems = computed(() => {
    if (hasActiveContext.value && activeContext.value) {
      const c = activeContext.value;
      return {
        items: c.items,
        parentPath: c.parentPath || "",
        title: c.label ?? null,
        description: c.description ?? null,
      };
    }
    if (
      layoutState.enableRouteBasedSubmenu &&
      layoutState.activeSubmenuContext
    ) {
      return layoutState.activeSubmenuContext;
    }
    return null;
  });

  const hasActiveSubitems = computed(() => {
    if (hasActiveContext.value && activeContext.value) {
      return !!(
        activeContext.value.items && activeContext.value.items.length > 0
      );
    }
    return !!(
      layoutState.enableRouteBasedSubmenu && layoutState.activeSubmenuContext
    );
  });

  // Drawer-like modes: Maestro (our styling) or drawer (original)
  const isDrawerLike = computed(
    () =>
      layoutConfig.menuMode === "drawer" || layoutConfig.menuMode === "maestro",
  );
  // Maestro only: vertical submenu strip + collapse sidebar when in submenu section
  const isMaestroMode = computed(() => layoutConfig.menuMode === "maestro");

  // Sidebar is icon-only when: Maestro mode + desktop + user collapsed it + we're in a submenu section
  const shouldCollapseSidebar = computed(
    () =>
      isMaestroMode.value &&
      isDesktop() &&
      !layoutState.sidebarExpanded &&
      hasActiveSubitems.value,
  );

  /**
   * Sync route to layout state (route-based fallback).
   * Only used when enableRouteBasedSubmenu is true and no context-config is active.
   * This maintains backward compatibility with existing route-based submenu detection.
   */
  function syncRouteToLayout(newPath) {
    // Skip route-based detection if context-config is active (context-config takes priority)
    if (hasActiveContext.value) {
      // Context-config is active; only collapse when subsidebar has items
      if (isMaestroMode.value) {
        const ctx = activeContext.value;
        const hasSubSidebar = ctx?.items?.length > 0;
        if (ctx) {
          layoutState.activePath = ctx.parentPath || null;
          layoutState.sidebarExpanded = !hasSubSidebar;
        } else {
          layoutState.activePath = null;
          layoutState.sidebarExpanded = true;
        }
      } else {
        layoutState.activePath = newPath;
      }
      return;
    }

    // Route-based fallback: active top-level parent drives subsidebar (root is never submenu parent)
    if (layoutState.enableRouteBasedSubmenu) {
      const root = menu.value?.find((n) => n.key === "root") ?? menu.value?.[0];
      const rootNode =
        root?.key === "root"
          ? root
          : menu.value?.length
            ? { items: menu.value }
            : null;
      const active = rootNode
        ? getActiveTopLevelParent(rootNode, newPath)
        : null;

      const companyMatch = newPath && newPath.match(/^\/companies\/(\d+)/);
      const companyId = companyMatch ? companyMatch[1] : null;

      const projectMatch =
        newPath && newPath.match(/^\/companies\/(\d+)\/projects\/(\d+)/);
      const projectCompanyId = projectMatch ? projectMatch[1] : null;
      const projectId = projectMatch ? projectMatch[2] : null;

      let ctx = null;
      let parentPath = "";

      // Project context: use dedicated project-context subtree when under a company project
      if (projectMatch && rootNode?.items?.length) {
        const projectContextNode = rootNode.items.find(
          (n) => n.key === "project-context",
        );
        const projectItems = projectContextNode?.items || [];
        parentPath = `/companies/${projectCompanyId}/projects/${projectId}`;
        if (projectItems.length) {
          ctx = {
            items: projectItems,
            parentPath,
            title: projectContextNode?.label ?? null,
            description: projectContextNode?.description ?? null,
          };
        }
      }

      // Fallback: regular top-level parent context (e.g. Companies, Settings)
      if (!ctx && active) {
        parentPath =
          active.parent.key === "companies" && companyId
            ? `/companies/${companyId}`
            : (active.parentPath ?? "");
        if (active.parent.key !== "root" && active.items?.length) {
          ctx = {
            items: active.items,
            parentPath,
            title: active.parent.label ?? null,
            description: active.parent.description ?? null,
          };
        }
      }

      layoutState.activeSubmenuContext = ctx;
      if (isMaestroMode.value) {
        const hasSubSidebar = ctx?.items?.length;
        if (ctx) {
          layoutState.activePath = active?.parent?.to ?? ctx.parentPath;
          layoutState.sidebarExpanded = !hasSubSidebar;
        } else {
          layoutState.activePath = null;
          layoutState.sidebarExpanded = true;
        }
      } else {
        layoutState.activePath = newPath;
      }
    } else {
      // Route-based detection disabled, clear any existing context
      layoutState.activeSubmenuContext = null;
      if (isMaestroMode.value) {
        layoutState.activePath = null;
        layoutState.sidebarExpanded = true;
      } else {
        layoutState.activePath = newPath;
      }
    }
  }

  // Watch for context changes to update sidebar state
  watch(
    () => hasActiveContext.value,
    (isActive) => {
      if (isMaestroMode.value) {
        if (isActive && activeContext.value) {
          const hasSubSidebar = (activeContext.value.items?.length ?? 0) > 0;
          layoutState.activePath = activeContext.value.parentPath || null;
          layoutState.sidebarExpanded = !hasSubSidebar;
        } else if (!isActive && !layoutState.enableRouteBasedSubmenu) {
          // Only auto-expand if route-based is disabled (otherwise route watcher handles it)
          layoutState.activePath = null;
          layoutState.sidebarExpanded = true;
        }
      }
    },
    { immediate: true },
  );

  // Watch route for backward compatibility (route-based fallback)
  watch(() => route?.path, syncRouteToLayout, { immediate: true });

  return {
    layoutConfig,
    layoutState,
    isDarkTheme,
    toggleConfigSidebar,
    toggleMenu,
    hasOpenOverlay,
    hasOverlaySubmenu,
    hasOpenOverlaySubmenu,
    hideMobileMenu,
    changeMenuMode,
    isHorizontal,
    isCompact,
    isSlim,
    isDesktop,
    isDrawerLike,
    isMaestroMode,
    hasActiveSubitems,
    activeSubitems,
    shouldCollapseSidebar,
  };
}
