"use client";
import Sidebar from "@/components/Layout/Sidebar";
import Loading from "@/components/Loading";
import { useSystemStore } from "@/stores/useSystemStore";
import { setHtmlFontSize } from "@/utils";
import { setCookies } from "@/utils/Cookies";
import { ConfigProvider, Dialog } from "antd-mobile";
import enUS from "antd-mobile/es/locales/en-US";
import { useLocale } from "next-intl";
import { ThemeProviderProps } from "next-themes/dist/types";
import { ReactNode, useLayoutEffect, useRef } from "react";
import { Swiper, SwiperClass, SwiperSlide } from "swiper/react";

import { useDebounceEffect } from "ahooks";
import { initializeApp } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
export interface ProvidersProps {
    children: ReactNode;
    themeProps?: Omit<ThemeProviderProps, "children">;
}

const initFirebase = () => {
    // 是否是https
    if (document.location.protocol.indexOf("https") === -1) return;
    //  浏览器是否支持 且是 pwa
    if (!window.Notification) {
        Dialog.alert({
            getContainer: null,
            bodyStyle: { background: "#fff" },
            title: "提示",
            confirmText: "我知道了",
            content: (
                <>
                    <div className={"text-center"}>
                        <p>当前版本浏览器不支持通知</p>
                        <p>请更换或升级浏览器获得更好使用体验</p>
                    </div>
                </>
            ),
        });
        return;
    }
    //  是否开启通知
    // new Notification("这是标题", {
    //     body: "这是正文",
    //     icon: "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png",
    //     requireInteraction: true,
    //     image: "https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png",
    // });
    if (Notification.permission === "default") {
        // 征求用户的许可
        Notification.requestPermission();
    }
    if (Notification.permission === "denied") return;

    const app = initializeApp({
        apiKey: process.env.NEXT_PUBLIC_FIREBASE_APIKEY,
        authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTHDOMAIN,
        projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECTID,
        storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGEBUCKET,
        messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGINGSENDERID,
        appId: process.env.NEXT_PUBLIC_FIREBASE_APPID,
        measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENTID,
    });
    const messaging = getMessaging(app);
    // 针对单机测试,或者服务端需要使用这个key可以放开
    // if (process.env.NODE_ENV === "development") {
    getToken(messaging, {
        vapidKey: process.env.NEXT_PUBLIC_FIREBASE_KEYS,
    }).then((res) => {
        console.log(`🚀🚀🚀🚀🚀-> `, res);
    });
    // }
    onMessage(messaging, (payload) => {
        const notifica = new Notification(payload.data?.title || "", {
            body: payload.data?.body,
            icon: payload.data?.image,
            ...payload.data,
        });
    });
};

const Layout = ({ children, themeProps }: ProvidersProps) => {
    const { isCollapse, setCollapse } = useSystemStore((state) => ({
        isCollapse: state.isCollapse,
        setCollapse: state.setCollapse,
    }));
    const local = useLocale();

    const swiperRef = useRef<SwiperClass>();
    const homeContainerRef = useRef<HTMLDivElement>(null);

    const startHandler = () => {
        homeContainerRef.current?.classList.add("containerMask");
        setCollapse(true);
    };
    const endHandler = () => {
        homeContainerRef.current?.classList.remove("containerMask");
        setCollapse(false);
    };

    useLayoutEffect(() => {
        // 调用响应式方法
        setHtmlFontSize();
        // 多语言兼容, 因为管理系统的静态数据是pt,但是页面路由需要br,  所以需要一致
        setCookies("language", local === "br" ? "pt" : local);
    }, []);

    return (
        <div id="app" className="bg-black">
            <Swiper
                resistanceRatio={10}
                initialSlide={2}
                slidesPerView={"auto"}
                onSlidePrevTransitionStart={startHandler}
                onSlideNextTransitionEnd={endHandler}
                slideToClickedSlide
                onSwiper={(swiper) => {
                    swiperRef.current = swiper;
                }}
                allowTouchMove={false}
            >
                <SwiperSlide>
                    <section className="relative flex h-[100vh] items-center justify-center">
                        <Loading />
                    </section>
                </SwiperSlide>

                <SwiperSlide style={{ width: "70%" }} className={"bg-[rgb(31,31,31)]"}>
                    <section className="relative h-[100vh]">{<Sidebar></Sidebar>}</section>
                </SwiperSlide>

                <SwiperSlide style={{ width: "100%" }}>
                    <section className="relative h-[100%]" ref={homeContainerRef}>
                        {children}
                    </section>
                </SwiperSlide>
            </Swiper>
        </div>
    );
};
export const Providers = ({ children, themeProps }: ProvidersProps) => {
    useDebounceEffect(() => {
        initFirebase();
    }, []);
    return (
        <ConfigProvider locale={enUS}>
            <Layout>{children}</Layout>
        </ConfigProvider>
    );
};
