import { createContext, useState, useContext, type ReactNode } from 'react';

import { parseAsStringEnum, useQueryState } from 'nuqs';
import { type PaletteMode } from '@material-hu/mui';

const themeParser = parseAsStringEnum<PaletteMode>(['light', 'dark']);

const SportsPoolThemeContext = createContext<PaletteMode | null>(null);

type SportsPoolThemeProviderProps = {
  children: ReactNode;
};

export const SportsPoolThemeProvider = ({
  children,
}: SportsPoolThemeProviderProps) => {
  // Read from URL on first render only. After the initial redirect strips
  // ?theme= from the URL, subsequent re-renders must not lose the value.
  const [themeFromUrl] = useQueryState('theme', themeParser);
  const [theme] = useState<PaletteMode | null>(themeFromUrl);

  return (
    <SportsPoolThemeContext.Provider value={theme}>
      {children}
    </SportsPoolThemeContext.Provider>
  );
};

export const useSportsPoolTheme = () => useContext(SportsPoolThemeContext);

export default SportsPoolThemeContext;
