import { useEffect, useState } from "react";
import { Client } from "@stomp/stompjs";

import type { ModuleSensorResponse } from "../../../types/meteo";

export type ClimateModuleResponse = {
    timestamp: string;
    sensors: ModuleSensorResponse[];
};

const WS_URL = "ws://localhost:18450/ws";
const TOPIC = "/topic/modules/climate/latest";

export function useClimateModuleStream() {
    const [module, setModule] = useState<ClimateModuleResponse | null>(null);
    const [connected, setConnected] = useState(false);
    const [lastTimestamp, setLastTimestamp] = useState<string | null>(null);

    useEffect(() => {
        const client = new Client({
            brokerURL: WS_URL,
            reconnectDelay: 3000,

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

                client.subscribe(TOPIC, (message) => {
                    const payload = JSON.parse(message.body) as ClimateModuleResponse;

                    setModule(payload);
                    setLastTimestamp(payload.timestamp);
                });
            },

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

            onStompError: (frame) => {
                console.error("Climate module STOMP error", frame);
                setConnected(false);
            },
        });

        client.activate();

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

    return {
        module,
        sensors: module?.sensors ?? [],
        sensorCount: module?.sensors.length ?? 0,
        connected,
        lastTimestamp,
    };
}