import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { PriceScenario } from "@/types";

interface SidebarCollapseState {
  presets: boolean;
  layouts: boolean;
  layers: boolean;
}

interface LayoutPersistState {
  /** Currently loaded layout ID in the editor (null = unsaved / new layout). */
  currentLayoutId: number | null;
  setCurrentLayoutId: (layoutId: number | null) => void;

  // Store last selected layout ID per scenario
  lastSelectedLayouts: Record<PriceScenario, number | null>;
  setLastSelectedLayout: (scenario: PriceScenario, layoutId: number | null) => void;
  getLastSelectedLayout: (scenario: PriceScenario) => number | null;

  // Sidebar sections collapsed state
  sidebarCollapsed: SidebarCollapseState;
  setSidebarCollapsed: (section: keyof SidebarCollapseState, collapsed: boolean) => void;
  toggleSidebarSection: (section: keyof SidebarCollapseState) => void;
}

export const useLayoutPersistStore = create<LayoutPersistState>()(
  persist(
    (set, get) => ({
      currentLayoutId: null,

      setCurrentLayoutId: (layoutId) => {
        set({ currentLayoutId: layoutId });
      },

      lastSelectedLayouts: {
        simple: null,
        sale: null,
        variable_simple: null,
        variable_sale: null,
      },

      setLastSelectedLayout: (scenario, layoutId) => {
        set((state) => ({
          lastSelectedLayouts: {
            ...state.lastSelectedLayouts,
            [scenario]: layoutId,
          },
        }));
      },

      getLastSelectedLayout: (scenario) => {
        return get().lastSelectedLayouts[scenario];
      },

      // Sidebar collapsed state - all sections expanded by default
      sidebarCollapsed: {
        presets: false,
        layouts: false,
        layers: false,
      },

      setSidebarCollapsed: (section, collapsed) => {
        set((state) => ({
          sidebarCollapsed: {
            ...state.sidebarCollapsed,
            [section]: collapsed,
          },
        }));
      },

      toggleSidebarSection: (section) => {
        set((state) => ({
          sidebarCollapsed: {
            ...state.sidebarCollapsed,
            [section]: !state.sidebarCollapsed[section],
          },
        }));
      },
    }),
    {
      name: "oppb-layout-selection", // localStorage key
      partialize: (state) => ({
        lastSelectedLayouts: state.lastSelectedLayouts,
        sidebarCollapsed: state.sidebarCollapsed,
      }),
    }
  )
);

// Helper function to check if a layout has any active location
export const hasAnyActiveLocation = (activeLocations: Record<string, boolean> | undefined | null): boolean => {
  if (!activeLocations) return false;
  return Object.values(activeLocations).some((isActive) => isActive === true);
};
