import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { db } from './database';
import { useLiveQuery } from 'dexie-react-hooks';

interface AppContextType {
  language: string;
  setLanguage: (lang: string) => void;
  themeMode: string;
  setThemeMode: (mode: string) => void;
}

const AppContext = createContext<AppContextType | undefined>(undefined);

export function AppProvider({ children }: { children: ReactNode }) {
  const settings = useLiveQuery(() => db.settings.toArray());
  const [language, setLanguageState] = useState('fi');
  const [themeMode, setThemeModeState] = useState('system');

  useEffect(() => {
    if (settings) {
      const lang = settings.find(s => s.key === 'language')?.value;
      const theme = settings.find(s => s.key === 'themeMode')?.value;
      if (lang) setLanguageState(lang);
      if (theme) setThemeModeState(theme);
    }
  }, [settings]);

  const setLanguage = async (lang: string) => {
    await db.settings.put({ key: 'language', value: lang });
    setLanguageState(lang);
  };

  const setThemeMode = async (mode: string) => {
    await db.settings.put({ key: 'themeMode', value: mode });
    setThemeModeState(mode);
  };

  useEffect(() => {
    const root = window.document.documentElement;
    root.classList.remove('light', 'dark');

    if (themeMode === 'system') {
      const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
      root.classList.add(systemTheme);
    } else {
      root.classList.add(themeMode);
    }
  }, [themeMode]);

  return (
    <AppContext.Provider value={{ language, setLanguage, themeMode, setThemeMode }}>
      {children}
    </AppContext.Provider>
  );
}

export function useAppContext() {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useAppContext must be used within an AppProvider');
  }
  return context;
}
