import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { safeStorage } from '../utils/safe-storage';

interface UserPreferences {
  unitSystem: 'imperial' | 'metric';
  darkMode: boolean;
  notifications: {
    email: boolean;
    push: boolean;
    maintenance: boolean;
  };
}

interface UserState {
  // User data (persisted subset)
  userProfile: {
    id: string;
    name: string;
    email: string;
    picture: string;
  } | null;

  preferences: UserPreferences;

  // Session data (not persisted)
  isOnline: boolean;
  lastSyncTimestamp: number;

  // Actions
  setUserProfile: (profile: any) => void;
  updatePreferences: (preferences: Partial<UserPreferences>) => void;
  setOnlineStatus: (isOnline: boolean) => void;
  updateLastSync: () => void;
  clearUserData: () => void;
}

export const useUserStore = create<UserState>()(
  persist(
    (set) => ({
      // Initial state
      userProfile: null,
      preferences: {
        unitSystem: 'imperial',
        darkMode: false,
        notifications: {
          email: true,
          push: true,
          maintenance: true,
        },
      },
      isOnline: true,
      lastSyncTimestamp: 0,

      // Actions
      setUserProfile: (profile) => {
        if (profile) {
          set({
            userProfile: {
              id: profile.sub,
              name: profile.name,
              email: profile.email,
              picture: profile.picture,
            },
          });
        }
      },

      updatePreferences: (newPreferences) => {
        set((state) => ({
          preferences: { ...state.preferences, ...newPreferences },
        }));
      },

      setOnlineStatus: (isOnline) => set({ isOnline }),

      updateLastSync: () => set({ lastSyncTimestamp: Date.now() }),

      clearUserData: () => set({
        userProfile: null,
        preferences: {
          unitSystem: 'imperial',
          darkMode: false,
          notifications: {
            email: true,
            push: true,
            maintenance: true,
          },
        },
      }),
    }),
    {
      name: 'motovaultpro-user-context',
      storage: createJSONStorage(() => safeStorage),
      partialize: (state) => ({
        userProfile: state.userProfile,
        preferences: state.preferences,
        // Don't persist session data
      }),
    }
  )
);