import { computed, getCurrentInstance, 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 a superadmin changes them under Superadmin → Theme & layout.
export const layoutConfig = reactive({
  // Preset shown under "Presets"
  preset: "Aura",
  // Color selected under "Primary"
  // (use one of the names from MaestroAppearanceSettingsPanel primaryColors)
  primary: "blue",
  // Custom primary hex when primary === "custom"
  primaryCustom: null,
  // Surface palette (see MaestroAppearanceSettingsPanel surfaces). When null, the UI
  // uses the default based on light/dark mode – typically the first "slate" option.
  surface: null,
  // Custom surface hex when surface === "custom"
  surfaceCustom: null,
  // Light/dark scheme — persisted app-wide from Superadmin → Theme & layout.
  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",
});

/**
 * Optionally align dark mode with the OS preference (hosts may call explicitly).
 * Core boot uses saved app settings instead of auto-listening to the OS.
 */
export function syncDarkThemeFromSystem() {
  if (typeof window === "undefined") return;
  const prefersDark = Boolean(
    window.matchMedia?.("(prefers-color-scheme: dark)")?.matches,
  );
  layoutConfig.darkTheme = prefersDark;
  document.documentElement.classList.toggle("app-dark", prefersDark);
}

const layoutState = reactive({
  staticMenuInactive: false,
  overlayMenuActive: 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 instance = getCurrentInstance();
  const route = instance
    ? useRoute()
    : { path: typeof window !== "undefined" ? window.location.pathname : "/" };
  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 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;

      const customerDetailMatch =
        newPath && newPath.match(/^\/customers\/(\d+)/);
      const customerDetailId = customerDetailMatch
        ? customerDetailMatch[1]
        : 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,
          };
        }
      }

      // Customer detail: vertical subsidebar (see .cursor/rules/maestro-subsidebar-navigation.mdc)
      if (!ctx && customerDetailId) {
        parentPath = `/customers/${customerDetailId}`;
        ctx = {
          items: [
            {
              key: "customer-show-dashboard",
              label: "Dashboard",
              to: `/customers/${customerDetailId}/dashboard`,
              exact: true,
            },
            {
              key: "customer-show-general",
              label: "Algemeen",
              to: `/customers/${customerDetailId}`,
              exact: true,
            },
            {
              key: "customer-show-contacts",
              label: "Contacten",
              to: `/customers/${customerDetailId}/contacts`,
            },
            {
              key: "customer-show-addresses",
              label: "Adressen",
              to: `/customers/${customerDetailId}/addresses`,
            },
            {
              key: "customer-show-offers",
              label: "Offertes",
              to: `/customers/${customerDetailId}/offers`,
            },
          ],
          parentPath,
          title: "Klant",
          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,
    toggleMenu,
    hasOpenOverlay,
    hasOverlaySubmenu,
    hasOpenOverlaySubmenu,
    hideMobileMenu,
    changeMenuMode,
    isHorizontal,
    isCompact,
    isSlim,
    isDesktop,
    isDrawerLike,
    isMaestroMode,
    hasActiveSubitems,
    activeSubitems,
    shouldCollapseSidebar,
  };
}
