import { useState, useEffect } from "react";

export interface ActivityData {
    hour: string;
    commands: number;
    transactions: number;
}

interface UseActivityStatsResult {
    data: ActivityData[];
    loading: boolean;
    error: string | null;
    refresh: () => Promise<void>;
}

/**
 * Custom hook to fetch hourly activity data for charts.
 * Data is cached on the server for 5 minutes.
 */
export function useActivityStats(): UseActivityStatsResult {
    const [data, setData] = useState<ActivityData[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const fetchActivity = async () => {
        setLoading(true);
        try {
            const response = await fetch("/api/stats/activity");
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            const jsonData = await response.json();
            setData(jsonData);
            setError(null);
        } catch (err) {
            console.error("Failed to fetch activity stats:", err);
            setError(err instanceof Error ? err.message : "Failed to fetch activity");
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchActivity();

        // Refresh every 5 minutes to match server cache
        const interval = setInterval(fetchActivity, 5 * 60 * 1000);
        return () => clearInterval(interval);
    }, []);

    return { data, loading, error, refresh: fetchActivity };
}
