import { useEffect, useState } from "react";
import { Client } from "@stomp/stompjs";
import type { DashboardOverview } from "../types/DashboardOverview";

export function useDashboardOverviewStream() {
  const [overview, setOverview] = useState<DashboardOverview | null>(null);
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    const client = new Client({
      brokerURL: "ws://localhost:18450/ws",
      reconnectDelay: 3000,

      onConnect: () => {
        setConnected(true);

        client.subscribe("/topic/dashboard/overview", (frame) => {
          const payload = JSON.parse(frame.body) as DashboardOverview;

          console.log("dashboard overview", payload);

          setOverview(payload);
        });
      },

      onWebSocketClose: () => {
        setConnected(false);
      },

      onStompError: () => {
        setConnected(false);
      },
    });

    client.activate();

    return () => {
      client.deactivate();
    };
  }, []);

  return {
    connected,
    overview,
  };
}