import { createContext, useContext, useEffect, useState } from "react";
import { usePage } from "@inertiajs/react";
import axios from "axios";

const ThemeProviderContext = createContext();

export function ThemeProvider({ children, apiRoute }) {
    const { auth, appearance } = usePage().props;

    const siteDefault = appearance?.default_theme || 'system';
    const userTheme = auth?.user?.theme;
    
    const initialTheme = userTheme && userTheme !== 'system' ? userTheme : siteDefault;

    const [theme, setThemeState] = useState(initialTheme);

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

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

    const setTheme = async (newTheme) => {
        setThemeState(newTheme);
        
        if (auth?.user) {
            const endpoint = apiRoute === 'admin' 
                ? '/api/admin/theme' 
                : '/api/user/theme';
            try {
                await axios.patch(endpoint, { theme: newTheme });
            } catch (error) {
                console.error("Failed to sync theme:", error);
            }
        }
    };

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

export const useTheme = () => {
    const context = useContext(ThemeProviderContext);
    if (context === undefined)
        throw new Error("useTheme must be used within a ThemeProvider");
    return context;
};