import { useApi } from "@/api";
import { PayloadUpdate, ResponseCreate } from "@/api/resources/Session";
import { ESourceAuthorization } from "@/api/resources/User";
import { getClientTimezone, language } from "@/locales";
import { actions, selectors } from "@/store";
import { useCallback, useMemo, useState } from "react"
import { useDispatch, useSelector } from "react-redux";


export const useSession = () => {
    const dispatch = useDispatch();
    const api = useApi();
    const session = useSelector(selectors.selectSession);

    const feature = useSelector(selectors.selectFeature)
    const { checked, dateOfCheck } = useSelector(selectors.selectPrivacyPolicy);
    const utm = useSelector(selectors.selectUTM);

    const timezone = getClientTimezone();

    const [isError, setIsError] = useState(false);

    const createSession = useCallback(async (source: ESourceAuthorization): Promise<ResponseCreate> => {
        if (session[source]?.length) {
            localStorage.setItem(`${source}_sessionId`, session[source]);
            return {
                sessionId: session[source],
                status: "old"
            }
        }
        try {
            const sessionParams = {
                feature,
                locale: language,
                timezone,
                source,
                sign: checked,
                signDate: dateOfCheck.length ? dateOfCheck : undefined,
                utm,
                domain: window.location.hostname
            };
            console.log('Creating session with parameters:', sessionParams);
            const sessionFromServer = await api.createSession(sessionParams);
            console.log('Session creation response:', sessionFromServer);
            if (sessionFromServer?.sessionId?.length && sessionFromServer?.status === "success") {
                dispatch(actions.session.update({
                    session: sessionFromServer.sessionId,
                    source
                }));
                localStorage.setItem(`${source}_sessionId`, sessionFromServer.sessionId);
                return sessionFromServer
            }
            console.error('Session creation failed - invalid response:', sessionFromServer);
            setIsError(true);
            return {
                status: "error",
                sessionId: ""
            }
        } catch (error) {
            console.error('Session creation failed with error:', error);
            setIsError(true);
            return {
                status: "error",
                sessionId: ""
            }
        }
    }, [api, checked, dateOfCheck, dispatch, feature, session, timezone, utm])

    const updateSession = useCallback(async (data: Omit<PayloadUpdate["data"], "feature">, source: ESourceAuthorization, sessionId?: string) => {
        try {
            const _sessionId = sessionId || session[source];
            const result = await api.updateSession({
                sessionId: _sessionId,
                data: {
                    feature,
                    ...data
                }
            });
            return result;
        } catch (error) {
            console.log(error)
        }
    }, [api, feature, session])

    const deleteSession = useCallback(async (source: ESourceAuthorization) => {
        localStorage.removeItem(`${source}_sessionId`);
        dispatch(actions.session.update({
            session: "",
            source
        }))
    }, [dispatch])

    return useMemo(() => ({
        session,
        isError,
        createSession,
        updateSession,
        deleteSession
    }), [
        session,
        isError,
        createSession,
        deleteSession,
        updateSession
    ])
}