import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { comms } from '@/communication';

export type Theme = 'dark' | 'PSH_PINK' | 'JW_SKY';

interface ThemeContextType {
    theme: Theme;
    setTheme: (theme: Theme) => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

const THEME_KEY = 'app-theme';

export function ThemeProvider({ children }: { children: ReactNode }) {
    const [theme, setTheme] = useState<Theme>(() => {
        const savedTheme = localStorage.getItem(THEME_KEY);
        return (savedTheme as Theme) || 'dark';
    });

    // 백엔드 설정 로드
    useEffect(() => {
        const loadSettings = async () => {
            try {
                const response = await comms.getSettings();
                if (response.Success && response.Data?.Theme) {
                    const savedTheme = response.Data.Theme as Theme;
                    if (['dark', 'PSH_PINK', 'JW_SKY'].includes(savedTheme)) {
                        setTheme(savedTheme);
                    }
                }
            } catch (error) {
                console.error('Failed to load theme from settings:', error);
            }
        };
        loadSettings();
    }, []);

    useEffect(() => {
        const root = window.document.documentElement;

        // 이전 테마 클래스 제거
        root.classList.remove('dark', 'theme-pink', 'theme-sky');

        // 새 테마 클래스 추가
        switch (theme) {
            case 'dark':
                root.classList.add('dark');
                break;
            case 'PSH_PINK':
                root.classList.add('theme-pink');
                break;
            case 'JW_SKY':
                root.classList.add('theme-sky');
                break;
        }

        localStorage.setItem(THEME_KEY, theme);
    }, [theme]);

    return (
        <ThemeContext.Provider value={{ theme, setTheme }}>
            {children}
        </ThemeContext.Provider>
    );
}

export function useTheme() {
    const context = useContext(ThemeContext);
    if (context === undefined) {
        throw new Error('useTheme must be used within a ThemeProvider');
    }
    return context;
}
