import { useState, useEffect } from 'react';
import { statsAPI } from '../utils/api';

export interface CategoryDistribution {
  name: string;
  count: number;
  quantity: number;
}

export interface MonthlyTrend {
  month: string;
  year: number;
  count: number;
}

export interface Analytics {
  totalVisits: number;
  itemsDistributed: number;
  wasteReduction: number;
  categoryDistribution: CategoryDistribution[];
  monthlyTrends: MonthlyTrend[];
  trends: {
    visitsChange: number;
    itemsChange: number;
    wasteChange: number;
  };
}

export const useAnalytics = () => {
  const [analytics, setAnalytics] = useState<Analytics>({
    totalVisits: 0,
    itemsDistributed: 0,
    wasteReduction: 0,
    categoryDistribution: [],
    monthlyTrends: [],
    trends: {
      visitsChange: 0,
      itemsChange: 0,
      wasteChange: 0
    }
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchAnalytics = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await statsAPI.getAnalytics();
      setAnalytics(data);
    } catch (err: any) {
      setError(err.message || 'Failed to fetch analytics');
      console.error('Analytics fetch error:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAnalytics();
  }, []);

  return { analytics, loading, error, refetch: fetchAnalytics };
};

