import { useEffect, useState } from "react";
import { fetchHistorianDashboard } from "../../../lib/api/historianApi";
import type { HistorianDashboardResponse } from "../../../types/historian";

type UseHistorianDashboardOptions = {
    keys: string[];
    minutesBack?: number;
    refreshIntervalMs?: number;
};

export function useHistorianDashboard({
    keys,
    minutesBack = 30,
    refreshIntervalMs = 15000,
}: UseHistorianDashboardOptions) {
    const [data, setData] = useState<HistorianDashboardResponse | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<Error | null>(null);

    useEffect(() => {
        let cancelled = false;

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

                const result = await fetchHistorianDashboard(
                    keys,
                    from.toISOString(),
                    to.toISOString(),
                );

                if (!cancelled) {
                    setData(result);
                    setError(null);
                }
            } catch (err) {
                if (!cancelled) {
                    setError(err instanceof Error ? err : new Error("Historian error"));
                }
            } finally {
                if (!cancelled) {
                    setLoading(false);
                }
            }
        }

        load();

        const interval = window.setInterval(load, refreshIntervalMs);

        return () => {
            cancelled = true;
            window.clearInterval(interval);
        };
    }, [keys.join("|"), minutesBack, refreshIntervalMs]);

    return { data, loading, error };
}