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

export type AccumulatedBucket = {
    label: string;
    from: string;
    to: string;
    total: number;
    unit?: string;
};

type AccumulatedRange = "7d" | "30d" | "month" | "year";

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

export function useAccumulatedHistory(
    sensor: ModuleSensorResponse | null,
    range: AccumulatedRange,
) {
    const [buckets, setBuckets] = useState<AccumulatedBucket[]>([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        if (!sensor || !sensor.key) {
            console.warn("[AccumulatedHistory SKIPPED] sensor is null or missing key", {
                sensor,
                range,
            });

            setBuckets([]);
            setLoading(false);
            return;
        }

        const controller = new AbortController();

        const sensorKey = sensor.key

        async function loadAccumulated() {
            setLoading(true);

            try {
                const params = new URLSearchParams({
                    key: sensorKey,
                    range,
                });

                const url = `${BACKEND_URL}/api/historian/accumulated?${params.toString()}`;

                const response = await fetch(url, {
                    method: "GET",
                    signal: controller.signal,
                    cache: "no-store",
                    headers: {
                        Accept: "application/json",
                        "Cache-Control": "no-cache",
                        Pragma: "no-cache",
                    },
                });

                const text = await response.text();

                if (!response.ok) {
                    throw new Error(
                        `Failed to load accumulated history: ${response.status} ${text}`,
                    );
                }

                const parsed = JSON.parse(text) as AccumulatedBucket[];

                if (!Array.isArray(parsed)) {
                    throw new Error("Accumulated history response is not an array");
                }

                const sortedPayload = [...parsed].sort(
                    (a, b) =>
                        new Date(a.from).getTime() -
                        new Date(b.from).getTime(),
                );
            
                setBuckets(sortedPayload);
            } catch (error) {
                if (controller.signal.aborted) return;

                console.error("[AccumulatedHistory ERROR]", error);
                setBuckets([]);
            } finally {
                if (!controller.signal.aborted) {
                    setLoading(false);
                }
            }
        }

        loadAccumulated();

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

    return {
        buckets,
        loading,
    };
}