import React, { FC, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { ThemeProvider as SCThemeProvider } from 'styled-components';

import { useMediaQuery } from '@material-ui/core';
import { ThemeProvider as MuiThemeProvider } from '@material-ui/core/styles';

import { selectTheme, setPreferredType } from './themeSlice';

const ThemeProvider: FC = ({ children }) => {
  const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
  const dispatch = useDispatch();
  const theme = useSelector(selectTheme);

  useEffect(() => {
    dispatch(setPreferredType(prefersDarkMode ? 'dark' : 'light'));
  }, [dispatch, prefersDarkMode]);

  return (
    <MuiThemeProvider theme={theme}>
      <SCThemeProvider theme={theme}> {children}</SCThemeProvider>
    </MuiThemeProvider>
  );
};

export default ThemeProvider;
