/**
 * KRA - App Model (Zustand Store)
 * Application configuration and theme management
 */
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { setBodyPrimaryColor } from '@/utils/format';

export type DarkMode = 'light' | 'dark' | 'auto';
export type SideMode = 'normal' | 'head' | 'combination';
export type TransitionType = 'slide' | 'fade' | 'zoom' | 'none';
export type GlobalSize = 'small' | 'default' | 'large';

export interface AppConfig {
  weakness: boolean;
  grey: boolean;
  primaryColor: string;
  showTabs: boolean;
  darkMode: DarkMode;
  layoutSideWidth: number;
  layoutSideCollapsedWidth: number;
  layoutSideItemHeight: number;
  showWatermark: boolean;
  sideMode: SideMode;
  transitionType: TransitionType;
  globalSize: GlobalSize;
}

interface AppState {
  device: 'desktop' | 'mobile' | '';
  drawerSize: string;
  operateMinWidth: string;
  collapsed: boolean;
  isDark: boolean;
  config: AppConfig;
}

interface AppActions {
  setDevice: (device: 'desktop' | 'mobile') => void;
  setCollapsed: (collapsed: boolean) => void;
  toggleCollapsed: () => void;
  setDarkMode: (mode: DarkMode) => void;
  toggleDark: () => void;
  setPrimaryColor: (color: string) => void;
  setWeakness: (weakness: boolean) => void;
  setGrey: (grey: boolean) => void;
  setShowTabs: (show: boolean) => void;
  setSideMode: (mode: SideMode) => void;
  setTransitionType: (type: TransitionType) => void;
  setGlobalSize: (size: GlobalSize) => void;
  setLayoutSideWidth: (width: number) => void;
  setLayoutSideCollapsedWidth: (width: number) => void;
  setShowWatermark: (show: boolean) => void;
  updateConfig: (config: Partial<AppConfig>) => void;
  resetConfig: () => void;
  applyTheme: () => void;
}

const defaultConfig: AppConfig = {
  weakness: false,
  grey: false,
  primaryColor: '#1890ff',
  showTabs: true,
  darkMode: 'auto',
  layoutSideWidth: 256,
  layoutSideCollapsedWidth: 80,
  layoutSideItemHeight: 48,
  showWatermark: true,
  sideMode: 'normal',
  transitionType: 'slide',
  globalSize: 'default',
};

export const useAppStore = create<AppState & AppActions>()(
  persist(
    (set, get) => ({
      device: '',
      drawerSize: '800',
      operateMinWidth: '240',
      collapsed: false,
      isDark: false,
      config: { ...defaultConfig },

      setDevice: (device) => {
        const isMobile = device === 'mobile';
        set({
          device,
          drawerSize: isMobile ? '100%' : '800',
          operateMinWidth: isMobile ? '80' : '240',
          collapsed: isMobile,
        });
      },

      setCollapsed: (collapsed) => set({ collapsed }),

      toggleCollapsed: () => set((state) => ({ collapsed: !state.collapsed })),

      setDarkMode: (mode) => {
        set((state) => ({
          config: { ...state.config, darkMode: mode },
        }));
        get().applyTheme();
      },

      toggleDark: () => {
        const { config } = get();
        const newMode = config.darkMode === 'dark' ? 'light' : 'dark';
        set((state) => ({
          config: { ...state.config, darkMode: newMode },
          isDark: newMode === 'dark',
        }));
        get().applyTheme();
      },

      setPrimaryColor: (color) => {
        set((state) => ({
          config: { ...state.config, primaryColor: color },
        }));
        get().applyTheme();
      },

      setWeakness: (weakness) => {
        set((state) => ({
          config: { ...state.config, weakness },
        }));
        document.documentElement.classList.toggle('html-weakness', weakness);
      },

      setGrey: (grey) => {
        set((state) => ({
          config: { ...state.config, grey },
        }));
        document.documentElement.classList.toggle('html-grey', grey);
      },

      setShowTabs: (show) => {
        set((state) => ({
          config: { ...state.config, showTabs: show },
        }));
      },

      setSideMode: (mode) => {
        set((state) => ({
          config: { ...state.config, sideMode: mode },
        }));
      },

      setTransitionType: (type) => {
        set((state) => ({
          config: { ...state.config, transitionType: type },
        }));
      },

      setGlobalSize: (size) => {
        set((state) => ({
          config: { ...state.config, globalSize: size },
        }));
      },

      setLayoutSideWidth: (width) => {
        set((state) => ({
          config: { ...state.config, layoutSideWidth: width },
        }));
      },

      setLayoutSideCollapsedWidth: (width) => {
        set((state) => ({
          config: { ...state.config, layoutSideCollapsedWidth: width },
        }));
      },

      setShowWatermark: (show) => {
        set((state) => ({
          config: { ...state.config, showWatermark: show },
        }));
      },

      updateConfig: (newConfig) => {
        set((state) => ({
          config: { ...state.config, ...newConfig },
        }));
        get().applyTheme();
      },

      resetConfig: () => {
        set({ config: { ...defaultConfig } });
        get().applyTheme();
      },

      applyTheme: () => {
        const { config } = get();
        let isDark = false;

        if (config.darkMode === 'auto') {
          isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        } else {
          isDark = config.darkMode === 'dark';
        }

        set({ isDark });

        // Apply dark mode class
        document.documentElement.classList.toggle('dark', isDark);

        // Apply primary color
        setBodyPrimaryColor(config.primaryColor, isDark ? 'dark' : 'light');

        // Apply weakness and grey
        document.documentElement.classList.toggle('html-weakness', config.weakness);
        document.documentElement.classList.toggle('html-grey', config.grey);
      },
    }),
    {
      name: 'kra-app-storage',
      partialize: (state) => ({
        config: state.config,
        collapsed: state.collapsed,
      }),
    }
  )
);

// Helper hooks
export const useIsDark = () => useAppStore((state) => state.isDark);
export const useConfig = () => useAppStore((state) => state.config);
export const useCollapsed = () => useAppStore((state) => state.collapsed);

export default useAppStore;
