import React, { useEffect } from "react";
import { PagePropsType, ToastType, WebSocketDataType } from "../types";
import useWebSocket from "@/twui/components/hooks/useWebSocket";
import useStatus from "@/twui/components/hooks/useStatus";
import useWebSocketEventHandler from "@/twui/components/hooks/useWebSocketEventHandler";
import { date } from "zod";

export default function useAppInit(pageProps: PagePropsType) {
    const { user } = pageProps;

    const [toast, setToast] = React.useState<ToastType>({
        toastOpen: false,
    });

    const { socket, sendData } = useWebSocket<WebSocketDataType>({
        url: "/ws",
        disableReconnect: false,
        keepAliveDuration: 5000,
    });

    const { loading, setLoading, refresh, setRefresh } = useStatus();

    const ws = { socket, sendData };

    const { data } = useWebSocketEventHandler<WebSocketDataType>();

    useEffect(() => {
        if (data?.event == "server:error") {
            setToast({
                toastOpen: true,
                toastMessage: data.message,
                toastStyle: "error",
            });
        }
        if (data?.event == "server:update") {
            setToast({
                toastOpen: true,
                toastMessage: data.message,
                toastStyle: "normal",
            });
        }
        if (data?.event == "server:success") {
            setToast({
                toastOpen: true,
                toastMessage: data.message,
                toastStyle: "success",
            });
        }
    }, [data]);

    return {
        socket,
        sendData,
        loading,
        setLoading,
        refresh,
        setRefresh,
        ws,
        user,
        pageProps,
        toast,
        setToast,
    };
}
