import { useState, useEffect } from 'react';

interface UserRatings {
  averageRating: number;
  totalReviews: number;
  isLoading: boolean;
  error: string | null;
}

export const useUserRatings = () => {
  const [ratings, setRatings] = useState<UserRatings>({
    averageRating: 0,
    totalReviews: 0,
    isLoading: true,
    error: null
  });

  useEffect(() => {
    const fetchRatings = async () => {
      try {
        setRatings(prev => ({ ...prev, isLoading: true, error: null }));
        
        const response = await fetch('/api/freelancer/ratings');
        
        if (!response.ok) {
          throw new Error('Failed to fetch ratings');
        }
        
        const data = await response.json();
        
        if (data.success) {
          setRatings({
            averageRating: data.data.averageRating,
            totalReviews: data.data.totalReviews,
            isLoading: false,
            error: null
          });
        } else {
          throw new Error(data.error || 'Failed to fetch ratings');
        }
      } catch (error) {
        console.error('Error fetching ratings:', error);
        setRatings({
          averageRating: 0,
          totalReviews: 0,
          isLoading: false,
          error: error instanceof Error ? error.message : 'Failed to fetch ratings'
        });
      }
    };

    fetchRatings();
  }, []);

  return ratings;
};