import { ThemeProvider, createTheme } from "@mui/material/styles";
import React from "react";
import { PropsWithChildren } from "react";
import { frFR as dataGridFr } from "@mui/x-data-grid/locales";

const localStorageKey = "dark-theme";

const darkTheme = createTheme(
  {
    palette: {
      mode: "dark",
    },
  },
  dataGridFr
);

const lightTheme = createTheme(
  {
    palette: {
      mode: "light",
    },
  },
  dataGridFr
);

interface DarkThemeContext {
  enabled: boolean;
  setEnabled: (enabled: boolean) => void;
}

const DarkThemeContextK = React.createContext<DarkThemeContext | null>(null);

export function DarkThemeProvider(p: PropsWithChildren): React.ReactElement {
  const [enabled, setEnabled] = React.useState(
    localStorage.getItem(localStorageKey) === "true"
  );

  return (
    <DarkThemeContextK.Provider
      value={{
        enabled: enabled,
        setEnabled(enabled) {
          localStorage.setItem(localStorageKey, enabled ? "true" : "false");
          setEnabled(enabled);
        },
      }}
    >
      <ThemeProvider theme={enabled ? darkTheme : lightTheme}>
        {p.children}
      </ThemeProvider>
    </DarkThemeContextK.Provider>
  );
}

export function useDarkTheme(): DarkThemeContext {
  return React.useContext(DarkThemeContextK)!;
}
