import { useState, useEffect } from 'react';
import {
  getDashboardData,
  type DashboardStats,
  type RecentActivity,
} from '../services/dashboardService';

interface UseDashboardReturn {
  stats: DashboardStats | null;
  recentActivity: RecentActivity[];
  isLoading: boolean;
  error: Error | null;
  refetch: () => Promise<void>;
}

/**
 * Hook for fetching and managing dashboard data
 * FE-PAGE-001: Complete Dashboard page implementation
 */
export function useDashboard(): UseDashboardReturn {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [recentActivity, setRecentActivity] = useState<RecentActivity[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  const fetchData = async () => {
    setIsLoading(true);
    setError(null);

    try {
      const data = await getDashboardData();
      setStats(data.stats);
      setRecentActivity(data.recent_activity);
    } catch (err) {
      setError(err instanceof Error ? err : new Error('Failed to fetch dashboard data'));
      // Set default values on error
      setStats({
        tracks_played: 0,
        messages_sent: 0,
        favorites: 0,
        active_friends: 0,
      });
      setRecentActivity([]);
    } finally {
      setIsLoading(false);
    }
  };

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

  return {
    stats,
    recentActivity,
    isLoading,
    error,
    refetch: fetchData,
  };
}

