import { useEffect, useRef } from "react";

import { getThemeColors } from "@/helpers/color";
import { removeCssVar, setCssVar } from "@/helpers/layout";
import { useStore } from "@/store";
import { type Theme, type ThemeColors } from "@/types";

interface ThemeOptions {
  scrollTransition?: boolean;
  overrideTheme?: Theme | null;
}

export default function useTheme(
  { scrollTransition, overrideTheme }: ThemeOptions = {
    scrollTransition: false,
  },
) {
  const currentTheme = useStore.use.currentTheme();
  const themeColors = useRef<ThemeColors>();

  function applyThemeColors(colors: ThemeColors) {
    Object.entries(colors).forEach(([key, value]) => {
      setCssVar(`color-${key}`, value);
    });
    themeColors.current = colors;
  }

  useEffect(() => {
    const themeToApply = overrideTheme || currentTheme;
    document.documentElement.setAttribute("data-theme", themeToApply);

    // Always apply theme colors immediately (scroll transitions disabled)
    const immediateThemeColors = getThemeColors(themeToApply);
    applyThemeColors(immediateThemeColors);
  }, [currentTheme, overrideTheme]);

  useEffect(() => {
    return () => {
      if (themeColors.current)
        Object.keys(themeColors.current).forEach((key) => {
          removeCssVar(`color-${key}`);
        });
    };
  }, []);
}
