import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';

interface ConnectionConfig {
  host: string;
  username: string;
  password?: string;
  port: number;
  database?: string;
}

interface AppState {
  darkMode: boolean;
  activeTab: string;
  activeDatabase: string | null;
  activeTable: string | null;
  dbTab: string; // 'tables', 'sql', 'import', 'export'
  connection: ConnectionConfig | null;
  connected: boolean;
  toggleDarkMode: () => void;
  setActiveTab: (tab: string) => void;
  setDbTab: (tab: string) => void;
  setConnection: (config: ConnectionConfig) => void;
  clearConnection: () => void;
  setActiveDatabase: (db: string | null) => void;
  setActiveTable: (table: string | null) => void;
}

export const useAppStore = create<AppState>()(
  persist(
    (set) => ({
      darkMode: true,
      activeTab: 'explorer',
      activeDatabase: null,
      activeTable: null,
      dbTab: 'tables',
      connection: null,
      connected: false,
      toggleDarkMode: () => set((state) => ({ darkMode: !state.darkMode })),
      setActiveTab: (tab) => set({ activeTab: tab }),
      setDbTab: (tab) => set({ dbTab: tab }),
      setConnection: (config) => set({ connection: config, connected: true }),
      clearConnection: () => set({ connection: null, connected: false, activeDatabase: null, activeTable: null }),
      setActiveDatabase: (db) => set({ activeDatabase: db, activeTable: null }),
      setActiveTable: (table) => set({ activeTable: table }),
    }),
    {
      name: 'mariavel-storage',
      storage: createJSONStorage(() => localStorage),
      // Persist crucial session state
      partialize: (state) => ({ 
        connection: state.connection, 
        connected: state.connected,
        darkMode: state.darkMode,
        activeDatabase: state.activeDatabase,
        activeTable: state.activeTable,
        activeTab: state.activeTab,
        dbTab: state.dbTab
      }),
    }
  )
);
