import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { AccountSettings } from '@/types/global';
import { SyncInterval, SYNC_INTERVALS, NotificationPreferences, ReadingPreferences } from '@/types/feed';

export interface SettingsState {
  // Sync Settings
  syncInterval: SyncInterval;
  setSyncInterval: (interval: SyncInterval) => void;
  
  // Theme Settings
  theme: 'system' | 'light' | 'dark';
  setTheme: (theme: 'system' | 'light' | 'dark') => void;
  
  // Notification Preferences
  notificationPreferences: NotificationPreferences;
  setNotificationPreferences: (prefs: Partial<NotificationPreferences>) => void;
  
  // Reading Preferences
  readingPreferences: ReadingPreferences;
  setReadingPreferences: (prefs: Partial<ReadingPreferences>) => void;
  
  // Account Settings
  accountSettings: AccountSettings;
  setAccountSettings: (settings: Partial<AccountSettings>) => void;
  
  // Actions
  resetSettings: () => void;
}

export const DEFAULT_SETTINGS = {
  syncInterval: SYNC_INTERVALS[2], // Default: Every 30 minutes
  theme: 'system',
  notificationPreferences: {
    newArticles: true,
    episodeReleases: true,
    customAlerts: false,
    badgeCount: true,
    sound: true,
    vibration: true,
  },
  readingPreferences: {
    fontSize: 'medium',
    lineHeight: 'normal',
    showTableOfContents: false,
    showReadingTime: true,
    showAuthor: true,
    showDate: true,
  },
  accountSettings: {
    email: '',
    notificationsEnabled: true,
    privacy: 'private',
    language: 'en-US',
    timezone: 'UTC',
    theme: 'system',
  },
} as const;

export const useSettingsStore = create<SettingsState>()(
  persist(
    (set, get) => ({
      ...DEFAULT_SETTINGS,
      setSyncInterval: (interval) => set({ syncInterval: interval }),
      setTheme: (theme) => set({ theme }),
      setNotificationPreferences: (prefs) =>
        set({
          notificationPreferences: {
            ...get().notificationPreferences,
            ...prefs,
          },
        }),
      setReadingPreferences: (prefs) =>
        set({
          readingPreferences: {
            ...get().readingPreferences,
            ...prefs,
          },
        }),
      setAccountSettings: (settings) =>
        set({
          accountSettings: {
            ...get().accountSettings,
            ...settings,
          },
        }),
      resetSettings: () => set(DEFAULT_SETTINGS),
    }),
    {
      name: 'rssuper-settings',
      partialize: (state) => ({
        syncInterval: state.syncInterval,
        theme: state.theme,
        notificationPreferences: state.notificationPreferences,
        readingPreferences: state.readingPreferences,
        accountSettings: state.accountSettings,
      }),
    }
  )
);

export default useSettingsStore;
