// React hook for fetching and managing statistics

import { useState, useEffect, useCallback } from 'react';
import { fetchStatistics, resetStatistics as resetStatsAPI } from '../api/client';
import type { Statistics } from '../types';

interface UseStatisticsReturn {
  statistics: Statistics | null;
  loading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  reset: () => Promise<void>;
  updateStatistics: (stats: Statistics) => void;
}

export const useStatistics = (): UseStatisticsReturn => {
  const [statistics, setStatistics] = useState<Statistics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadStatistics = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const stats = await fetchStatistics();
      setStatistics(stats);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load statistics');
      console.error('Error loading statistics:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  // Initial load
  useEffect(() => {
    loadStatistics();
  }, [loadStatistics]);

  const refresh = useCallback(async () => {
    await loadStatistics();
  }, [loadStatistics]);

  const reset = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      await resetStatsAPI();

      // Reset local statistics
      setStatistics({
        total_events: 0,
        total_tools_used: 0,
        total_agents: 0,
        total_sessions: 0,
        last_updated: Date.now() / 1000,
      });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to reset statistics');
      console.error('Error resetting statistics:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  const updateStatistics = useCallback((stats: Statistics) => {
    setStatistics(stats);
  }, []);

  return {
    statistics,
    loading,
    error,
    refresh,
    reset,
    updateStatistics,
  };
};

export default useStatistics;
