import React, { createContext, ReactElement, useEffect, useState } from "react";

type Theme = "light" | "dark";

const ThemeContext = createContext<{
  theme: Theme;
  setTheme(newTheme: Theme): void;
}>({
  theme: "light",
  setTheme: () => {
    throw new Error("Use ThemeProvider instead.");
  },
});

interface Props {
  theme: Theme;
  children?: ReactElement;
}

export function ThemeProvider({ children, theme }: Props) {
  const [currentTheme, setTheme] = useState(theme);

  useEffect(() => {
    if (currentTheme === "light") {
      document.body.classList.remove("dark");
    } else if (currentTheme === "dark") {
      document.body.classList.add("dark");
    }
  }, [currentTheme]);

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