import { useQuery } from '@tanstack/react-query';
import { systemAccountsApi, categorizeAccounts } from '../api/system-accounts.api';
import { useMemo } from 'react';

/**
 * Hook to fetch all system accounts
 */
export function useSystemAccounts() {
  return useQuery({
    queryKey: ['system-accounts'],
    queryFn: systemAccountsApi.getList,
  });
}

/**
 * Hook to fetch system accounts summary (includes mining config and circulation pool)
 */
export function useSystemAccountsSummary() {
  return useQuery({
    queryKey: ['system-accounts', 'summary'],
    queryFn: systemAccountsApi.getSummary,
  });
}

/**
 * Hook to get categorized system accounts for display
 */
export function useCategorizedAccounts() {
  const { data, ...rest } = useSystemAccounts();

  const categorized = useMemo(() => {
    if (!data?.accounts) {
      return {
        mainPools: [],
        systemAccounts: [],
        fixedAccounts: [],
        otherAccounts: [],
      };
    }
    return categorizeAccounts(data.accounts);
  }, [data?.accounts]);

  return {
    ...rest,
    data: categorized,
    total: data?.total ?? 0,
  };
}

/**
 * Hook to fetch system account mining records
 */
export function useSystemAccountMiningRecords(
  accountType: string,
  page: number = 1,
  pageSize: number = 20
) {
  return useQuery({
    queryKey: ['system-accounts', accountType, 'records', page, pageSize],
    queryFn: () => systemAccountsApi.getMiningRecords(accountType, page, pageSize),
    enabled: !!accountType,
  });
}

/**
 * Hook to fetch system account transactions
 */
export function useSystemAccountTransactions(
  accountType: string,
  page: number = 1,
  pageSize: number = 20
) {
  return useQuery({
    queryKey: ['system-accounts', accountType, 'transactions', page, pageSize],
    queryFn: () => systemAccountsApi.getTransactions(accountType, page, pageSize),
    enabled: !!accountType,
  });
}
