/**
 * @ai-summary React hooks for user profile management
 */

import React from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { profileApi } from '../api/profile.api';
import { UpdateProfileRequest } from '../types/profile.types';
import toast from 'react-hot-toast';

interface ApiError {
  response?: {
    data?: {
      error?: string;
    };
  };
  message?: string;
}

export const useProfile = () => {
  const { isAuthenticated, isLoading } = useAuth0();

  const query = useQuery({
    queryKey: ['user-profile'],
    queryFn: async () => {
      const response = await profileApi.getProfile();
      return response.data;
    },
    enabled: isAuthenticated && !isLoading,
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 10 * 60 * 1000, // 10 minutes cache time
    retry: (failureCount, error: any) => {
      if (error?.response?.status === 401 && failureCount < 3) {
        return true;
      }
      return false;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
    refetchOnWindowFocus: false,
    refetchOnMount: false,
  });

  React.useEffect(() => {
    if (query.data) {
      console.log('[useProfile] Profile loaded successfully');
    }
    if (query.error) {
      console.error('[useProfile] Error loading profile:', query.error);
    }
  }, [query.data, query.error]);

  return query;
};

export const useUpdateProfile = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: UpdateProfileRequest) => profileApi.updateProfile(data),
    onSuccess: (response) => {
      queryClient.setQueryData(['user-profile'], response.data);
      toast.success('Profile updated successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to update profile');
    },
  });
};
