import { useApi } from "@/api";
import { useAuth } from "@/auth/useAuth";
import { actions } from "@/store";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { useLocation, useSearchParams } from "react-router-dom";

interface InitializationProviderProps {
    children: React.ReactNode;
}

export function InitializationProvider({ children }: InitializationProviderProps) {
    const location = useLocation();
    const [isInitialized, setIsInitialized] = useState(false);
    const [searchParams] = useSearchParams();
    const jwtToken = searchParams.get("token");
    const api = useApi();
    const { signUp, logout, token, user } = useAuth();
    const dispatch = useDispatch();

    useEffect(() => {
        const initialize = async () => {
            if (!jwtToken) {
                setIsInitialized(true);
                return;
            }

            try {
                logout();
                const { token } = await api.getRealToken({ token: jwtToken });
                const { user } = await api.getUser({ token });
                const { user: userMe } = await api.getMe({ token });
                signUp(token, user, userMe);
            } catch (error) {
                console.log("Error of get real token or get user: ");
                console.error(error);
            } finally {
                setIsInitialized(true);
            }
        };

        initialize();
    }, [api, jwtToken, logout, signUp]);

    useEffect(() => {
        (async () => {
            if (!token.length || !user) return;
            const {
                user: { has_subscription },
            } = await api.getSubscriptionStatus({
                token,
            });

            const { subscription: subscriptionStatusNew } =
                await api.getSubscriptionStatusNew({ token });

            if ((has_subscription || subscriptionStatusNew) && user) {
                return dispatch(actions.status.update("subscribed"));
            }
            if (!has_subscription && !subscriptionStatusNew && user) {
                return dispatch(actions.status.update("unsubscribed"));
            }
            if (!user) {
                return dispatch(actions.status.update("lead"));
            }
        })();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [dispatch, api, token, location.pathname]);

    if (!isInitialized) {
        return null;
    }

    return <>{children}</>;
}