import { JsonObject } from '@win2win/shared';
import { get, set } from 'lodash';
import { defineStore } from 'pinia';
import { Tab } from 'src/components/common-ww/btns/tabs';
import { LayoutContext, LayoutType } from 'src/models';
import { AppLayoutView } from 'src/widgets/useLayout';

type LayoutKey = `${LayoutContext}_${LayoutType}`;
type DynamicLayoutState = {
  [key in LayoutKey]: {
    currentView: AppLayoutView | null;
    tabs: Tab[];
    contextParams: Record<string, any>;
  };
};

type LayoutOptions = {
  context: LayoutContext;
  type: LayoutType;
};

export const useDynamicLayoutStore = defineStore('Dynamiclayout', {
  state: (): Partial<DynamicLayoutState> => ({}),
  actions: {
    setCurrentView(view: AppLayoutView | null, options: LayoutOptions) {
      const key = getLayoutKey(options);
      set(this, [key, 'currentView'], view);
    },
    setTabs(tabs: Tab[], options: LayoutOptions) {
      const key = getLayoutKey(options);
      set(this, [key, 'tabs'], tabs);
    },
    setContextParams(params: JsonObject, options: LayoutOptions) {
      const key = getLayoutKey(options);
      set(this, [key, 'contextParams'], { ...(get(this, [key, 'contextParams']) || {}), ...params });
    },
  },
  getters: {
    currentView: (state) => (options: LayoutOptions) => {
      return get(state, [getLayoutKey(options), 'currentView'], null) as AppLayoutView | null;
    },
    tabs: (state) => (options: LayoutOptions) => {
      return get(state, [getLayoutKey(options), 'tabs'], []) as Tab[];
    },
    contextParams: (state) => (options: LayoutOptions) => {
      return get(state, [getLayoutKey(options), 'contextParams'], {}) as JsonObject;
    },
  },
});

const getLayoutKey = (options: LayoutOptions): LayoutKey => {
  return `${options.context}_${options.type}` as LayoutKey;
};
