import "@ant-design/v5-patch-for-react-19";
import { Layout, Skeleton, ConfigProvider, Badge } from "antd";
import { User } from "firebase/auth";
import { useEffect, useState, FC } from "react";
import { ErrorBoundary } from "react-error-boundary";
import { Provider } from "react-redux";
import { HashRouter, Route, Routes } from "react-router";
import ipcTypes from "../../util/ipcTypes.json";
import ErrorBoundaryFallback from "./components/ErrorBoundaryFallback/ErrorBoundaryFallback";
import Settings from "./components/Settings/Settings";
import SignInForm from "./components/SignInForm/SignInForm";
import UpdateAvailable from "./components/UpdateAvailable/UpdateAvailable";
import reduxStore from "./redux/redux-store";
import { auth } from "./util/firebase";
import { NotificationProvider } from "./util/notificationContext";

const App: FC = () => {
  const [user, setUser] = useState<User | boolean | null>(false);
  useEffect(() => {
    // Only set up the listener once when component mounts
    if (auth.currentUser) {
      setUser(auth.currentUser);
    } else {
      setUser(false);
    }
    const unsubscribe = auth.onAuthStateChanged((user: User | null) => {
      setUser(user);
      //Send back to the main process so that it knows we are authenticated.
      if (user) {
        window.electron.ipcRenderer.send(
          ipcTypes.toMain.authStateChanged,
          user.toJSON(),
        );
        window.electron.ipcRenderer.send(ipcTypes.toMain.watcher.start);
      }
    });

    // Clean up the listener when component unmounts
    return (): void => unsubscribe();
  }, []);

  const isTest = window.api.isTest();

  return (
    <ConfigProvider
      theme={{
        token: {},
        components: {
          Card: {
            borderRadius: 8,
            colorBgBase: "#ffaacc",
            boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
          },
        },
      }}
    >
      <Provider store={reduxStore}>
        <HashRouter>
          <ErrorBoundary FallbackComponent={ErrorBoundaryFallback}>
            <NotificationProvider>
              <Skeleton loading={user === false} active>
                <Layout style={{ minHeight: "100vh" }}>
                  {!user ? (
                    <SignInForm />
                  ) : (
                    <Badge.Ribbon
                      text={isTest && "Connected to Test"}
                      color={isTest ? "red" : undefined}
                    >
                      <Layout.Content style={{ padding: "0 24px" }}>
                        <UpdateAvailable />
                        <Routes>
                          <Route path="/" element={<Settings />} />
                        </Routes>
                      </Layout.Content>
                    </Badge.Ribbon>
                  )}
                </Layout>
              </Skeleton>
            </NotificationProvider>
          </ErrorBoundary>
        </HashRouter>
      </Provider>
    </ConfigProvider>
  );
};

export default App;
