import { ApolloProvider } from "@apollo/client";
import { App as AntdApp, ConfigProvider, theme } from "antd";
import enLocale from "antd/es/locale/en_US";
import React, { useEffect } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import LoadingSpinnerAtom from "../components/atoms/loading-spinner/loading-spinner.atom";
import RoutesPage from "../components/pages/routes/routes.page";
import SignInPage from "../components/pages/sign-in/sign-in.page";
import client from "../graphql/GraphQLClient";
import ipcTypes from "../ipc.types";
import "../ipc/ipc-renderer-handler";
import { checkUserSession } from "../redux/user/user.actions";
import { selectCurrentUser, selectDarkMode } from "../redux/user/user.selectors";
import { loadErrorMessages, loadDevMessages } from "@apollo/client/dev";
import { configureAntdFeedback } from "../util/antdFeedback";
import "./App.styles.scss";
const { ipcRenderer } = window;

if (process.env.NODE_ENV !== "production") {
  // Adds messages only in a dev environment
  loadDevMessages();
  loadErrorMessages();
}

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser,
  darkMode: selectDarkMode
});
const mapDispatchToProps = (dispatch) => ({
  checkUserSession: () => dispatch(checkUserSession())
});

function AntdFeedbackBridge() {
  const { message, notification } = AntdApp.useApp();

  useEffect(() => {
    configureAntdFeedback({ message, notification });
  }, [message, notification]);

  return null;
}

export function App({ currentUser, checkUserSession, darkMode }) {
  useEffect(() => {
    checkUserSession();
  }, [checkUserSession]);

  useEffect(() => {
    if (currentUser && currentUser.email) {
      ipcRenderer.send(ipcTypes.app.toMain.setUserName, currentUser.email);
    }
  }, [currentUser]);

  useEffect(() => {
    //
    return () => {
      ipcRenderer.send(ipcTypes.fileWatcher.toMain.stop);
    };
  }, []);

  if (currentUser.authorized === null) {
    return <LoadingSpinnerAtom />;
  }

  return (
    <ApolloProvider client={client}>
      <ConfigProvider
        componentSize="small"
        theme={{
          algorithm: darkMode ? theme.darkAlgorithm : theme.defaultAlgorithm
        }}
        input={{ autoComplete: "new-password" }}
        locale={enLocale}
      >
        <AntdApp>
          <AntdFeedbackBridge />
          <div>{currentUser.authorized ? <RoutesPage /> : <SignInPage />}</div>
        </AntdApp>
      </ConfigProvider>
    </ApolloProvider>
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
