import { useEffect } from 'react';
import { useAuthStore } from '../stores/authStore';
import { useUserProfile } from './useUserProfile';
import { useUserWallet } from './useUserWallet';

/**
 * Custom hook that integrates the auth store with profile and wallet hooks
 * This maintains the existing functionality while using Zustand for state management
 */
export const useAuthWithProfile = () => {
  const {
    user,
    loading,
    phoneSessionInfo,
    phoneConfirmationResult,
    phoneLoading,
    phoneError,
    setProfile,
    setWallet,
    setProfileLoading,
    setWalletLoading,
    setProfileError,
    setWalletError,
    setFormattedBalance,
    setPhoneSessionInfo,
    setPhoneConfirmationResult,
    setPhoneLoading,
    setPhoneError,
    clearPhoneAuth,
    signOut,
  } = useAuthStore();

  // Use the existing profile hook
  const profileHook = useUserProfile(user);
  const walletHook = useUserWallet(user);

  // Sync profile hook data with store - batch updates to reduce re-renders
  useEffect(() => {
    // Batch state updates to avoid multiple re-renders
    setProfile(profileHook.profile);
    setProfileLoading(profileHook.loading);
    setProfileError(profileHook.error);
  }, [profileHook.profile, profileHook.loading, profileHook.error, setProfile, setProfileLoading, setProfileError]);

  // Sync wallet hook data with store - batch updates to reduce re-renders
  useEffect(() => {
    // Batch state updates to avoid multiple re-renders
    setWallet(walletHook.wallet);
    setWalletLoading(walletHook.loading);
    setWalletError(walletHook.error);
    setFormattedBalance(walletHook.formattedBalance);
  }, [walletHook.wallet, walletHook.loading, walletHook.error, walletHook.formattedBalance, setWallet, setWalletLoading, setWalletError, setFormattedBalance]);


  return {
    // Auth state
    user,
    loading,

    // Profile state - use hook values directly
    profile: profileHook.profile,
    profileLoading: profileHook.loading,
    profileError: profileHook.error,

    // Wallet state - use hook values directly
    wallet: walletHook.wallet,
    walletLoading: walletHook.loading,
    walletError: walletHook.error,
    formattedBalance: walletHook.formattedBalance,

    // Phone auth state
    phoneSessionInfo,
    phoneConfirmationResult,
    phoneLoading,
    phoneError,

    // Actions
    signOut,
    refreshProfile: profileHook.refreshProfile,
    refreshWallet: walletHook.refreshWallet,

    // Phone auth actions
    setPhoneSessionInfo,
    setPhoneConfirmationResult,
    setPhoneLoading,
    setPhoneError,
    clearPhoneAuth,

    // Wallet actions
    addCreditCard: walletHook.addCreditCard,
    removeCreditCard: walletHook.removeCreditCard,
    balanceInDollars: walletHook.balanceInDollars,
  };
};
