import { useApi } from "@/api";
import { ESourceAuthorization } from "@/api/resources/User";
import { useAuth } from "@/auth/useAuth";
import { useSession } from "@/hooks/session/useSession";
import metricService from "@/services/metric/metricService";
import { actions } from "@/store";
import { getSourceByPathname } from "@/utils/source.utils";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { useLocation, useSearchParams } from "react-router-dom";
import { FlagProvider } from '@unleash/proxy-client-react';
import { handLandmarkerSingleton } from "@/utils/handLandmarkerSingleton";

interface InitializationProviderProps {
    children: React.ReactNode;
}

const availableSourcesForSession = [
    ESourceAuthorization["aura.palmistry"],
    ESourceAuthorization["aura.palmistry.new"],
    ESourceAuthorization["aura.chats"],
    ESourceAuthorization["aura.compatibility.v2"],
    ESourceAuthorization["aura.compatibility.v3"],
    ESourceAuthorization["aura.test.payment"]
]

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();
    const {
        // isError: isErrorSession, session,
        createSession
    } = useSession()
    const source = getSourceByPathname();
    // const localesPlacement = getLocalesPlacementByPathname();

    // useEffect(() => {
    //     if (!token.length || !localesPlacement) return;
    //     (async () => {
    //         console.log(localesPlacement);
            
    //         const result = await api.getFunnel({
    //             token,
    //             funnel: localesPlacement
    //         })
    //         console.log(result);

    //     })()
    // }, [token, localesPlacement])


    useEffect(() => {
        handLandmarkerSingleton.preload();
    }, []);

    useEffect(() => {
        const createSessionBySource = async () => {
            if (!availableSourcesForSession.includes(source)) {
                return;
            }
            const session = await createSession(
                source
            );
            if (session?.sessionId?.length) {
                metricService.userParams({
                    sessionId: session.sessionId,
                });
            }
        }
        createSessionBySource();
    }, [])

    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
        // || (!session?.[source] && !isErrorSession)
    ) {
        return null;
    }

    const config = {
        url: import.meta.env.AURA_UNLEASH_URL, // Your front-end API URL or the Unleash proxy's URL (https://<proxy-url>/proxy)
        clientKey: import.meta.env.AURA_UNLEASH_CLIENT_KEY, // A client-side API token OR one of your proxy's designated client keys (previously known as proxy secrets)
        refreshInterval: 15, // How often (in seconds) the client should poll the proxy for updates
        appName: 'aura', // The name of your application. It's only used for identifying your application
    };

    return <>
        <FlagProvider config={config}>
            {children}
        </FlagProvider>
    </>;
}