import { useCallback, useEffect, useMemo, useRef } from 'react';
import { Transaction } from '../services/transactionService';
import { useTransactionStore } from '../stores/transactionStore';
import type { TransactionCacheEntry } from '../stores/transactionStore';
import { useGlobalLoading } from './useGlobalLoading';

export interface UseTransactionsReturn {
  transactions: Transaction[];
  loading: boolean;
  error: string | null;
  refreshTransactions: () => Promise<void>;
}

const defaultEntry: TransactionCacheEntry = {
  transactions: [],
  loading: false,
  error: null,
};

export const useTransactions = (uid: string | undefined): UseTransactionsReturn => {
  const userId = uid ?? null;
  const lastUidRef = useRef<string | null>(null);

  const ensureSubscription = useTransactionStore((state) => state.ensureSubscription);
  const refreshFromStore = useTransactionStore((state) => state.refreshTransactions);
  const removeTransactions = useTransactionStore((state) => state.removeTransactions);
  const { withLoading } = useGlobalLoading();

  const entry = useTransactionStore(
    useCallback(
      (state) => (userId ? state.transactionsByUid[userId] ?? defaultEntry : defaultEntry),
      [userId]
    )
  );

  useEffect(() => {
    if (lastUidRef.current && lastUidRef.current !== userId) {
      removeTransactions(lastUidRef.current);
    }
    lastUidRef.current = userId;
  }, [userId, removeTransactions]);

  useEffect(() => {
    if (!userId) {
      return;
    }
    ensureSubscription(userId);
  }, [ensureSubscription, userId]);

  const refreshTransactions = useCallback(async () => {
    if (!userId) {
      return;
    }
    await withLoading(() => refreshFromStore(userId));
  }, [refreshFromStore, userId, withLoading]);

  return useMemo(
    () => ({
      transactions: userId ? entry.transactions : [],
      loading: userId ? entry.loading : false,
      error: userId ? entry.error : null,
    refreshTransactions,
    }),
    [entry.error, entry.loading, entry.transactions, refreshTransactions, userId]
  );
};

export default useTransactions;
