import { useState, useEffect } from 'react';
import { useApiClient } from '../utils/apiClient';

interface UserProfile {
  display_name?: string | null;
  handle?: string | null;
  email?: string | null;
}

export function useUserProfile() {
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const apiClient = useApiClient();

  useEffect(() => {
    const fetchProfile = async () => {
      try {
        setIsLoading(true);
        setError(null);
        
        // Try to get user profile from Suno API
        const { data, error: apiError } = await apiClient.GET('/api/user/me');
        
        if (apiError) {
          throw new Error('Failed to fetch user profile');
        }
        
        if (data) {
          setProfile({
            display_name: data.display_name,
            handle: data.handle,
            email: data.email
          });
        }
      } catch (err) {
        console.error('Error fetching user profile:', err);
        setError(err instanceof Error ? err.message : 'Unknown error');
      } finally {
        setIsLoading(false);
      }
    };

    fetchProfile();
  }, [apiClient]);

  const getDisplayName = (): string => {
    if (profile?.display_name) {
      return profile.display_name;
    }
    
    if (profile?.handle) {
      return profile.handle;
    }
    
    return 'Someone';
  };

  return {
    profile,
    isLoading,
    error,
    displayName: getDisplayName()
  };
}