'use client'
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { usePathname } from "next/navigation";
import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react";
import Cookies from 'js-cookie'
import { useQuery } from "@tanstack/react-query";
import { ChatAppID, ChatAuthKey, ChatRegion, SelfAPI } from "@/Utils/APIRequest/Endpoints";
import CustomFetch from "@/Utils/APIRequest/AxiosInstance";
import { getUserDetails } from "@/lib/Features/UserDetails/userDetails"
import Sidebar from "./Sidebar";
import Header from "./Header";
import HeaderProfileSidebar from "./Header/HeaderProfileSidebar";
import { setChatUserData } from "@/lib/Features/CometChatSlice/cometChatSlice";
import { InfluencerProvider } from "@/Utils/InfluencerContext";

const hasAuthSession = () =>
    !!(Cookies.get('iat') || Cookies.get('bat') || Cookies.get('aat') || Cookies.get('verifyUAT'));

const MainLayoutPage = ({ children }: Readonly<{ children: React.ReactNode; }>) => {
    const pathName = usePathname();
    const dispatch = useDispatch();
    const [hideHeader, setHideHeader] = useState(false);
    const { data, isPending, refetch } = useQuery({
        queryKey: [SelfAPI],
        queryFn: () => CustomFetch({ url: SelfAPI }, null, false),
        refetchOnWindowFocus: false,
        enabled: hasAuthSession(),
        select: (data) => data?.data,
    });

    useEffect(() => {
        if (data) {
            dispatch(getUserDetails(data))
        }
    }, [isPending, data]);

    const InitializationCometChat = (userData) => {
        if (!ChatAppID || !ChatRegion || !ChatAuthKey) {
            console.error('CometChat initialization failed: Missing required configuration', {
                ChatAppID: ChatAppID || 'MISSING',
                ChatRegion: ChatRegion || 'MISSING',
                ChatAuthKey: ChatAuthKey ? 'PRESENT' : 'MISSING'
            });
            return;
        }

        const UIKitSettings = new UIKitSettingsBuilder()
            .setAppId(ChatAppID)
            .setRegion(ChatRegion)
            .setAuthKey(ChatAuthKey)
            .subscribePresenceForAllUsers()
            .build();

        CometChatUIKit.init(UIKitSettings)
            ?.then(() => {
                // console.log("Initialization completed successfully");
                CometChatUIKit.getLoggedinUser().then((loggedInUser) => {
                    if (!loggedInUser) {
                        CometChatUIKit.login(userData?.role == "admin" ? "admin" : userData?.id)
                            .then((user) => {
                                console.log("Login Successful", { user });
                                Cookies.set("cc_auth",
                                    user?.getAuthToken() ?? "", {
                                    expires: 7,
                                    secure: true,
                                    sameSite: "strict"
                                });
                                CometChatUIKit.SoundManager.play("incomingMessageFromOther", "/assets/audio/notification-ring.wav")
                                dispatch(setChatUserData(user))
                            })
                            .catch((error) => console.error("Login failed", error));
                    } else {
                        Cookies.set("cc_auth",
                            loggedInUser?.getAuthToken() ?? "", {
                            expires: 7,
                            secure: true,
                            sameSite: "strict"
                        });
                        dispatch(setChatUserData(loggedInUser))
                    }
                });
            })
            .catch((error) => console.error("Initialization failed", error));
    }

    useEffect(() => {
        let userInfoCookie = Cookies.get('first_time');
        userInfoCookie = userInfoCookie && JSON.parse(userInfoCookie);
        if (data?.id) {
            InitializationCometChat(data)
        }

        if (pathName.includes('brand/dashboard') || pathName.includes('influencer/dashboard')) {
            setHideHeader(true)
        } else {
            setHideHeader(false)
        }
    }, [pathName, data?.id, data?.role])

    return (
        <InfluencerProvider>
            <div className="bg-surfaceMuted min-h-screen">
                <Header hideHeader={hideHeader} />
                <Sidebar />
                <main className={`${hideHeader ? '2xl:!pr-72 xl:!pr-[19.5rem] md:h-[calc(100vh-92px)] h-[calc(100vh-52px)]' : 'md:pt-8 pt-4 md:pb-6 pb-4 xl:h-[calc(100vh-92px)] md:h-[calc(100vh-70px)] h-[calc(100vh-62px)]'} w-full overflow-y-auto 2xl:px-16 xl:px-12 md:px-8 px-4 2xl:ps-80 xl:ps-72 relative transition-all scrollbar-hide ${pathName.includes('brand/messages') ? 'max-md:px-0  max-md:pb-0 max-md:bg-white' : ''} `}>
                    {children}
                </main>
                <HeaderProfileSidebar hideHeader={hideHeader} />
            </div>
        </InfluencerProvider>
    )
}

export default MainLayoutPage
