import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { UIState, Notification } from '@/types';

interface UIActions {
  setTheme: (theme: 'light' | 'dark' | 'system') => void;
  setLanguage: (language: 'en' | 'fr') => void;
  setSidebarOpen: (open: boolean) => void;
  addNotification: (
    notification: Omit<Notification, 'id' | 'timestamp'>
  ) => void;
  removeNotification: (id: string) => void;
  markNotificationAsRead: (id: string) => void;
  clearNotifications: () => void;
}

export const useUIStore = create<UIState & UIActions>()(
  persist(
    set => ({
      // État initial
      theme: 'system',
      language: 'en',
      sidebarOpen: true,
      notifications: [],

      // Actions
      setTheme: theme => {
        set({ theme });
        // Appliquer le thème au DOM
        const root = document.documentElement;
        if (theme === 'system') {
          const prefersDark = window.matchMedia(
            '(prefers-color-scheme: dark)'
          ).matches;
          root.classList.toggle('dark', prefersDark);
        } else {
          root.classList.toggle('dark', theme === 'dark');
        }
      },

      setLanguage: language => {
        set({ language });
        // Synchroniser avec i18n
        if (typeof window !== 'undefined' && window.i18n) {
          window.i18n.changeLanguage(language);
        }
      },

      setSidebarOpen: sidebarOpen => set({ sidebarOpen }),

      addNotification: notification => {
        const newNotification: Notification = {
          ...notification,
          id: crypto.randomUUID(),
          timestamp: new Date().toISOString(),
        };
        set(state => ({
          notifications: [...state.notifications, newNotification],
        }));
      },

      removeNotification: id => {
        set(state => ({
          notifications: state.notifications.filter(n => n.id !== id),
        }));
      },

      markNotificationAsRead: id => {
        set(state => ({
          notifications: state.notifications.map(n =>
            n.id === id ? { ...n, read: true } : n
          ),
        }));
      },

      clearNotifications: () => set({ notifications: [] }),
    }),
    {
      name: 'ui-storage',
      partialize: state => ({
        theme: state.theme,
        language: state.language,
        sidebarOpen: state.sidebarOpen,
      }),
    }
  )
);
