import { createContext } from "preact";
import { useContext } from "preact/compat";
import { useEffect, useState } from "preact/hooks";
import { fetchUserInfo } from "../../api";
import { useQuery } from "react-query";

type TColorScheme = "light" | "dark";

type TColorSchemeContext = {
    colorScheme: TColorScheme;
};

const ColorSchemeContext = createContext({ colorScheme: "light" } as TColorSchemeContext);

export const ColorSchemeProvider = ({ children }) => {
    const { data } = useQuery({ ...fetchUserInfo() });
    const [activeScheme, setActiveScheme] = useState<TColorScheme>("light");

    useEffect(() => {
        const preference = data?.preferences?.dashboard_color_scheme || "system";

        if (preference === "system") {
            const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
            const handleChange = () => {
                setActiveScheme(mediaQuery.matches ? "dark" : "light");
            };

            handleChange();
            mediaQuery.addEventListener("change", handleChange);
            return () => mediaQuery.removeEventListener("change", handleChange);
        } else {
            setActiveScheme(preference as TColorScheme);
        }
    }, [data]);

    return (
        <ColorSchemeContext.Provider value={{ colorScheme: activeScheme }}>
            {children}
        </ColorSchemeContext.Provider>
    );
};

export const useColorScheme = () => useContext(ColorSchemeContext);
