import { useEffect } from "react";
import { useAppSelector, useAppDispatch } from "../store/hooks";
import { toggleTheme, setTheme } from "../store/slices/uiSlice";
import { setAccentColor } from "../utils/colorUtils";

export const useTheme = () => {
  const theme = useAppSelector((state) => state.ui.theme);
  const accentColor = useAppSelector((state) => state.ui.accentColor);
  const dispatch = useAppDispatch();

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    setAccentColor(accentColor);

    const themeColorMeta = document.querySelector('meta[name="theme-color"]');
    if (themeColorMeta) {
      themeColorMeta.setAttribute(
        "content",
        theme === "dark" ? "#1a1a1a" : accentColor
      );
    }
  }, [theme, accentColor]);

  useEffect(() => {
    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
    const handler = (e: MediaQueryListEvent) => {
      if (!localStorage.getItem("theme")) {
        dispatch(setTheme(e.matches ? "dark" : "light"));
      }
    };
    mediaQuery.addEventListener("change", handler);
    return () => mediaQuery.removeEventListener("change", handler);
  }, [dispatch]);

  return {
    theme,
    accentColor,
    toggleTheme: () => dispatch(toggleTheme()),
  };
};
