import { cloneDeep, omit } from 'lodash';
import { defineStore } from 'pinia';

import { LayoutConfig } from 'src/pages/layout/models';
import { Component } from 'vue';
export interface DrawerState {
  show: boolean;
  component: Component | null;
  props: any;
  width: string;
  title: string;
  prevState: Omit<DrawerState, 'prevState'> | null;
}
export interface LayoutState {
  config: Partial<LayoutConfig> | null;
  mainDrawer: DrawerState;
}

export const useLayoutConfigStore = defineStore('LayoutConfig', {
  persist: {
    key: 'layout-config-store',
    paths: ['config'],
  },
  state: (): LayoutState => ({
    config: null,
    mainDrawer: {
      show: false,
      width: '400px',
      title: '',
      component: null,
      props: {},
      prevState: null,
    },
  }),
  actions: {
    setConfig(value: Partial<LayoutConfig>) {
      this.config = value;
    },
    setDrawer(data: { payload: Partial<DrawerState>; saveState: boolean }) {
      const { payload, saveState = false } = data;
      if (!payload) {
        return;
      }
      Object.assign(this.mainDrawer, payload);
      if (saveState) {
        this.mainDrawer.prevState = cloneDeep(omit(this.mainDrawer, 'prevState'));
      }
    },

    backToPrevDrawerState() {
      const prevState = this.mainDrawer.prevState;
      if (!prevState) return;
      Object.assign(this.mainDrawer, prevState);
    },

    showDrawer() {
      if (!this.mainDrawer) return;
      this.mainDrawer.show = true;
    },
    hideDrawer() {
      if (!this.mainDrawer) return;
      this.mainDrawer.show = false;
      this.mainDrawer.component = null;
      this.mainDrawer.props = {};
      this.mainDrawer.title = '';
    },
  },
  getters: {
    configExists: (state) => !!state.config,
    menuConfig: (state) => state.config?.menu || [],
    homeConfig: (state) => state.config?.home || {},
    loginConfig: (state) => state.config?.login || {},
    stylesConfig: (state) => state.config?.styles || [],
    toolbarConfig: (state) => state.config?.toolbar || {},
    footerConfig: (state) => state.config?.footer || {},
    drawer: (state) => state.mainDrawer,
  },
});
