import { ApolloProvider } from "@apollo/client";
import { ConfigProvider } 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 } from "../redux/user/user.selectors";
import "./App.styles.scss";
const { ipcRenderer } = window;

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

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

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

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

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