import { useEffect, useState } from "react";
import type { ModuleSensorResponse } from "../../../types/meteo";
import type { HistorianPoint } from "../components/MeteoHistoryModal";

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

type SensorHistoryMap = Record<string, HistorianPoint[]>;

export function useMeteoMultiHistory(
    sensors: Array<ModuleSensorResponse | null>,
    hours = 6,
) {
    const [pointsByKey, setPointsByKey] = useState<SensorHistoryMap>({});
    const [loading, setLoading] = useState(false);

    const sensorKeys = sensors
        .filter((sensor): sensor is ModuleSensorResponse => Boolean(sensor))
        .map((sensor) => sensor.key);

    useEffect(() => {
        if (!sensorKeys.length) {
            setPointsByKey({});
            return;
        }

        const controller = new AbortController();

        async function loadHistory() {
            try {
                setLoading(true);

                const to = new Date();
                const from = new Date(to.getTime() - hours * 60 * 60 * 1000);

                const entries = await Promise.all(
                    sensorKeys.map(async (key) => {
                        const params = new URLSearchParams({
                            key,
                            from: from.toISOString(),
                            to: to.toISOString(),
                        });

                        const response = await fetch(
                            `${BACKEND_URL}/api/historian/series?${params.toString()}`,
                            { signal: controller.signal },
                        );

                        if (!response.ok) {
                            throw new Error(`Failed to load history for ${key}`);
                        }

                        const payload = (await response.json()) as HistorianPoint[];

                        return [key, payload] as const;
                    }),
                );

                setPointsByKey(Object.fromEntries(entries));
            } catch (error) {
                if (controller.signal.aborted) return;

                console.error("Failed to load meteo histories", error);
                setPointsByKey({});
            } finally {
                if (!controller.signal.aborted) {
                    setLoading(false);
                }
            }
        }

        loadHistory();

        return () => controller.abort();
    }, [sensorKeys.join("|"), hours]);

    return {
        pointsByKey,
        loading,
    };
}