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

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

export function useMeteoHistory(sensor: ModuleSensorResponse | null) {
    const [hours, setHours] = useState(1);
    const [points, setPoints] = useState<HistorianPoint[]>([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        if (!sensor) {
            setPoints([]);
            return;
        }

        const sensorKey = sensor.key;
        const controller = new AbortController();

        async function loadHistory() {
            try {
                const to = new Date();
                const from = new Date(to.getTime() - hours * 60 * 60 * 1000);

                const params = new URLSearchParams({
                    key: sensorKey,
                    from: from.toISOString(),
                    to: to.toISOString(),
                });

                setLoading(true);

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

                if (!response.ok) {
                    throw new Error("Failed to load history");
                }

                const payload = (await response.json()) as HistorianPoint[];
                setPoints(payload);
            } catch (error) {
                if (controller.signal.aborted) return;

                console.error("Failed to load meteo history", error);
                setPoints([]);
            } finally {
                if (!controller.signal.aborted) {
                    setLoading(false);
                }
            }
        }

        loadHistory();

        return () => {
            controller.abort();
        };
    }, [sensor?.key, hours]);

    return {
        points,
        loading,
        hours,
        setHours,
    };
}