import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter, Navigate, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import { CssBaseline, ThemeProvider } from "@mui/material";
import Faq from "./pages/Faq/Faq";
import Wallet from "./pages/Wallet";
import Payment from "./pages/Payment/Payment";
import Support from "./pages/Support/Support";
import AccountSettings from "./pages/AccountSettings/AccountSettings";
import Landing from "./pages/Landing/Landing";
import Tariffs from "./pages/Tariffs/Tariffs";
import SigninDialog from "./pages/auth/Signin";
import SignupDialog from "./pages/auth/Signup";
import PaymentHistory from "./pages/PaymentHistory/PaymentHistory";
import Basket from "./pages/Basket/Basket";
import TariffPage from "./pages/Tariffs/TariffsPage";
import lightTheme from "@utils/themes/light";
import PrivateRoute from "@utils/routes/privateRoute";
import reportWebVitals from "./reportWebVitals";
import { SnackbarProvider, enqueueSnackbar } from "notistack";
import "./index.css";
import Layout from "./components/Layout";
import { clearUserData, setUser, setUserAccount, useUserStore } from "./stores/user";
import TariffConstructor from "./pages/TariffConstructor/TariffConstructor";
import { useUser } from "./utils/hooks/useUser";
import { clearAuthToken, getMessageFromFetchError } from "@frontend/kitui";
import { useUserAccount } from "./utils/hooks/useUserAccount";
import { setCustomTariffs } from "@root/stores/customTariffs";
import { useCustomTariffs } from "@root/utils/hooks/useCustomTariffs";
import { useDiscounts } from "./utils/hooks/useDiscounts";
import { setDiscounts } from "./stores/discounts";


const App = () => {
    const location = useLocation();
    const userId = useUserStore(state => state.userId);
    const navigate = useNavigate();

    useCustomTariffs({
        url: "https://admin.pena.digital/strator/privilege/service",
        onNewUser: setCustomTariffs,
        onError: error => {
            const errorMessage = getMessageFromFetchError(error, "Не удалось получить кастомные тарифы");
            if (errorMessage) enqueueSnackbar(errorMessage);
        }
    });

    useUser({
        url: `https://hub.pena.digital/user/${userId}`,
        userId,
        onNewUser: setUser,
        onError: error => {
            const errorMessage = getMessageFromFetchError(error);
            if (errorMessage) {
                enqueueSnackbar(errorMessage);
                clearUserData();
                clearAuthToken();
            }
        }
    });

    useUserAccount({
        url: "https://hub.pena.digital/customer/account",
        userId,
        onNewUserAccount: setUserAccount,
        onError: error => {
            const errorMessage = getMessageFromFetchError(error);
            if (errorMessage) {
                enqueueSnackbar(errorMessage);
                clearUserData();
                clearAuthToken();
                navigate("/signin");
            }
        }
    });

    useDiscounts({
        onNewDiscounts: setDiscounts,
        onError: error => {
            const message = getMessageFromFetchError(error);
            if (message) enqueueSnackbar(message);
        }
    });

    if (location.state?.redirectTo) return <Navigate to={location.state.redirectTo} replace state={{ backgroundLocation: location }} />;

    return (
        <>
            {location.state?.backgroundLocation &&
                <Routes>
                    <Route path="/signin" element={<SigninDialog />} />
                    <Route path="/signup" element={<SignupDialog />} />
                </Routes>
            }
            <Routes location={location.state?.backgroundLocation || location}>
                <Route path="/" element={<Landing />} />
                <Route path="/signin" element={<Navigate to="/" replace state={{ redirectTo: "/signin" }} />} />
                <Route path="/signup" element={<Navigate to="/" replace state={{ redirectTo: "/signup" }} />} />
                <Route element={<Layout />}>
                    <Route element={<PrivateRoute />}>
                        <Route path="/tariffs" element={<Tariffs />} />
                        <Route path="/tariffs/time" element={<TariffPage />} />
                        <Route path="/tariffs/volume" element={<TariffPage />} />
                        <Route path="/faq" element={<Faq />} />
                        <Route path="/support" element={<Support />} />
                        <Route path="/support/:ticketId" element={<Support />} />
                        <Route path="/tariffconstructor" element={<TariffConstructor />} />
                        <Route path="/basket" element={<Basket />} />
                        <Route path="/wallet" element={<Wallet />} />
                        <Route path="/payment" element={<Payment />} />
                        <Route path="/settings" element={<AccountSettings />} />
                        <Route path="/paymenthistory" element={<PaymentHistory />} />
                    </Route>
                </Route>
            </Routes>
        </>
    );
};

const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
root.render(
    <React.StrictMode>
        <ThemeProvider theme={lightTheme}>
            <BrowserRouter>
                <CssBaseline />
                <SnackbarProvider />
                <App />
            </BrowserRouter>
        </ThemeProvider>
    </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
