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

const BACKEND_URL = "http://localhost:18450";

export function useTelemetryStream() {
  const [message, setMessage] = useState<TelemetryBroadcastMessage | null>(null);
  const [connected, setConnected] = useState(false);
  const [initialLoading, setInitialLoading] = useState(true);

  useEffect(() => {
    const controller = new AbortController();

    async function loadInitialLatest() {
      try {
        const response = await fetch(`${BACKEND_URL}/api/telemetry/latest`, {
          signal: controller.signal,
          cache: "no-store",
          headers: {
            Accept: "application/json",
          },
        });

        if (!response.ok) {
          throw new Error(`Failed to load latest telemetry: ${response.status}`);
        }

        const payload = (await response.json()) as TelemetryBroadcastMessage;

        console.log("[TelemetryStream INITIAL]", payload);

        setMessage(payload);
      } catch (error) {
        if (controller.signal.aborted) return;

        console.error("[TelemetryStream INITIAL ERROR]", error);
      } finally {
        if (!controller.signal.aborted) {
          setInitialLoading(false);
        }
      }
    }

    loadInitialLatest();

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

      onConnect: () => {
        console.log("[TelemetryStream WS CONNECTED]");
        setConnected(true);

        client.subscribe("/topic/telemetry/latest", (frame) => {
          const payload = JSON.parse(frame.body) as TelemetryBroadcastMessage;

          console.log("[TelemetryStream WS MESSAGE]", payload);

          setMessage(payload);
          setInitialLoading(false);
        });
      },

      onWebSocketClose: () => {
        console.warn("[TelemetryStream WS CLOSED]");
        setConnected(false);
      },

      onStompError: (frame) => {
        console.error("[TelemetryStream STOMP ERROR]", frame);
        setConnected(false);
      },
    });

    client.activate();

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

  return {
    connected,
    initialLoading,
    message,
    lastTimestamp: message?.timestamp ?? null,
    snapshots: message?.snapshots ?? [],
    sensorCount: message?.sensorCount ?? 0,
  };
}