import { useState, useEffect } from 'react';
import { adminApi } from '@/services/adminApi';
import { useToast } from '@/hooks/use-toast';

interface AnalyticsOverview {
  totalUsers: number;
  totalRevenue: number;
  totalBookings: number;
  activeEstablishments: number;
  topDestinations: Array<{
    id: string;
    name: string;
    visits: number;
  }>;
  revenueByCategory: Array<{
    category: string;
    revenue: number;
  }>;
  userGrowth: Array<{
    date: string;
    users: number;
  }>;
  conversionRate: number;
}

export const useAnalytics = (period: string = 'month') => {
  const [analytics, setAnalytics] = useState<AnalyticsOverview | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();

  const loadAnalytics = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await adminApi.getAnalyticsOverview(period);
      setAnalytics(data as AnalyticsOverview);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Error al cargar analytics';
      setError(errorMessage);
      toast({
        title: 'Error',
        description: errorMessage,
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadAnalytics();
  }, [period]);

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