import {useMatch, useMatches, useSearch} from "@tanstack/react-router";
import {useEffect} from "react";
import {useSelector} from "react-redux";
import {RootState, useAppDispatch} from "../../redux/store.ts";
import {OpenAPI} from "../../client";
import PageWrapper from "../PageWrapper/PageWrapper.tsx";
import {LoadingOverlay} from "@mantine/core";
import {AnimatePresence} from "framer-motion";
import AnimatedOutlet from "../../components/AnimatedOutlet/au.tsx";
import {SearchParams} from "../../shared/lib/general.ts";
import {login} from "../../features/authSlice.ts";

const RootPage = () => {

    const search: SearchParams = useSearch({strict: false});
    const dispatch = useAppDispatch();
    const matches = useMatches();
    const match = useMatch({strict: false});
    const nextMatchIndex = matches.findIndex((d) => d.id === match.id) + 1;
    const nextMatch = matches[nextMatchIndex];

    const authState = useSelector((state: RootState) => state.auth);
    const uiState = useSelector((state: RootState) => state.ui);
    const rewriteLocalStorage = () => {
        const jsonData = JSON.stringify(authState);
        localStorage.setItem('authState', jsonData);
    }
    const setOpenApiToken = () => {
        OpenAPI.TOKEN = authState.accessToken;
    }
    useEffect(() => {
        rewriteLocalStorage();
        setOpenApiToken();
    }, [authState]);
    useEffect(() => {
        if (!search.accessToken) return;
        dispatch(login({accessToken: search.accessToken.toString()}))
    }, [search])
    return (
        <>
            <LoadingOverlay visible={uiState.isLoading}/>
            <PageWrapper>
                <AnimatePresence mode="popLayout">
                    <AnimatedOutlet key={nextMatch.id}/>
                </AnimatePresence>
            </PageWrapper>

        </>
    )
}

export default RootPage;