import { useEffect, useState, useRef } from "react";
import type { DashboardStats } from "@shared/modules/dashboard/dashboard.types";

export function useSocket() {
    const [isConnected, setIsConnected] = useState(false);
    const [stats, setStats] = useState<DashboardStats | null>(null);
    const socketRef = useRef<WebSocket | null>(null);

    useEffect(() => {
        // Determine WS protocol based on current page schema
        const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
        const host = window.location.host;
        const wsUrl = `${protocol}//${host}/ws`;

        function connect() {
            const ws = new WebSocket(wsUrl);
            socketRef.current = ws;

            ws.onopen = () => {
                console.log("Connected to dashboard websocket");
                setIsConnected(true);
            };

            ws.onmessage = (event) => {
                try {
                    const payload = JSON.parse(event.data);

                    if (payload.type === "STATS_UPDATE") {
                        setStats(payload.data);
                    }
                } catch (err) {
                    console.error("Failed to parse WS message", err);
                }
            };

            ws.onclose = () => {
                console.log("Disconnected from dashboard websocket");
                setIsConnected(false);
                // Simple reconnect logic
                setTimeout(connect, 3000);
            };

            ws.onerror = (err) => {
                console.error("WebSocket error:", err);
                ws.close();
            };
        }

        connect();

        return () => {
            if (socketRef.current) {
                // Prevent reconnect on unmount
                socketRef.current.onclose = null;
                socketRef.current.close();
            }
        };
    }, []);

    return { isConnected, stats };
}
