import React from 'react';
import { ReactNode, createContext, useMemo, useState } from 'react';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import type { PaletteMode } from '@mui/material';

type ThemeContextType = {
  toggleColorMode: () => void;
};

type ThemeProviderProps = {
  children: ReactNode;
};

export const ThemeContext = createContext<ThemeContextType>({
  toggleColorMode: () => {},
});

function ThemeContextProvider({ children }: ThemeProviderProps) {
  const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
  const [mode, setMode] = useState<'light' | 'dark'>(
    prefersDarkMode ? 'dark' : 'light'
  );

  const toggleColorMode = () => {
    setMode((prevMode: PaletteMode) =>
      prevMode === 'light' ? 'dark' : 'light'
    );
  };

  const getDesignTokens = (mode: PaletteMode) => ({
    palette: {
      mode,
      ...(mode === 'light'
        ? {
            primary: {
              main: '#FFAB91',
            },
          }
        : {
            primary: {
              main: '#FF8A65',
            },
          }),
    },
  });

  const colorTheme = createTheme(getDesignTokens(mode));

  const theme = useMemo(
    () =>
      createTheme({
        ...colorTheme,
        typography: {
          fontFamily: ['Playwrite US Trad', 'cursive'].join(','),
          button: {
            textTransform: 'none',
          },
          body1: {
            lineHeight: 1.8,
          },
        },
        components: {
          MuiInputBase: {
            defaultProps: {
              sx: {
                fontFamily: 'Roboto, sans-serif',
              },
            },
          },
          MuiInputLabel: {
            defaultProps: {
              sx: {
                fontFamily: 'Roboto, sans-serif',
              },
            },
          },
        },
      }),
    [mode]
  );

  return (
    <ThemeContext.Provider value={{ toggleColorMode }}>
      <ThemeProvider theme={theme}>{children}</ThemeProvider>
    </ThemeContext.Provider>
  );
}

export default ThemeContextProvider;
