import React, { createContext, useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';

import { TOKEN_KEY, USER_KEY, WATCH_SHARED_DATA_KEY } from '@/modules/@common/watch/constants';
import { APPEARANCE_MODE_DARK, APPEARANCE_MODE_LIGHT } from '@/mui/constants';
import { cookiesKey, defaultSettings } from '@/mui/constants/config';

import { getToken } from '@/modules/@common/token/helpers';
import { userDataForWatch } from '@/modules/@common/user/redux/selectors';
import { set } from '@/mui/helpers/cookie';

const SettingsContext = createContext({
  ...defaultSettings,
  onToggleMode: () => {},
});

function SettingsProvider(props) {
  const [settings, setSettings] = useState(props.defaultSettings);
  const userData = useSelector(userDataForWatch);
  const providerSettings = useMemo(
    () => ({
      ...settings,
      onToggleMode: () => {
        setSettings({
          ...settings,
          themeMode: settings.themeMode === APPEARANCE_MODE_LIGHT ? APPEARANCE_MODE_DARK : APPEARANCE_MODE_LIGHT,
        });
      },
    }),
    [settings, setSettings],
  );

  useEffect(() => {
    set(cookiesKey.themeMode, settings.themeMode);
  }, [settings]);

  useEffect(() => {
    if (getToken() && userData) {
      window.parent.postMessage(
        {
          type: WATCH_SHARED_DATA_KEY,
          [TOKEN_KEY]: getToken(),
          [USER_KEY]: userData,
        },
        '*',
      );
    }
  }, [userData]);

  return <SettingsContext.Provider value={providerSettings}>{props.children}</SettingsContext.Provider>;
}

SettingsProvider.propTypes = {
  children: PropTypes.node.isRequired,
  defaultSettings: PropTypes.shape({}).isRequired,
};

export { SettingsProvider, SettingsContext };
