import { createContext, createSignal, onMount, useContext, type ParentComponent } from "solid-js";

type ThemeMode = "light" | "dark";

type ThemeContextType = {
	mode: () => ThemeMode;
	toggleMode: () => void;
	isReady: () => boolean;
};

const THEME_STORAGE_KEY = "boostai-color-mode";
const ThemeContext = createContext<ThemeContextType>();

const getInitialMode = (): ThemeMode => {
	if (typeof window === "undefined") return "light";

	const storedMode = window.localStorage.getItem(THEME_STORAGE_KEY);
	if (storedMode === "light" || storedMode === "dark") return storedMode;

	const attributeMode = document.documentElement.getAttribute("data-color-scheme");
	if (attributeMode === "light" || attributeMode === "dark") return attributeMode;

	return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
};

export const ThemeProvider: ParentComponent = (props) => {
	const [mode, setMode] = createSignal<ThemeMode>("light");
	const [isReady, setIsReady] = createSignal(false);

	const applyMode = (nextMode: ThemeMode) => {
		setMode(nextMode);
		document.documentElement.setAttribute("data-color-scheme", nextMode);
		window.localStorage.setItem(THEME_STORAGE_KEY, nextMode);
	};

	const toggleMode = () => {
		applyMode(mode() === "light" ? "dark" : "light");
	};

	onMount(() => {
		applyMode(getInitialMode());
		setIsReady(true);
	});

	return <ThemeContext.Provider value={{ mode, toggleMode, isReady }}>{props.children}</ThemeContext.Provider>;
};

export const useTheme = () => {
	const context = useContext(ThemeContext);
	if (!context) {
		throw new Error("useTheme must be used within ThemeProvider");
	}

	return context;
};
