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,
  referenceType?: string | null,
) {
  return useQuery({
    queryKey: ['system-accounts', accountType, 'transactions', page, pageSize, referenceType],
    queryFn: () => systemAccountsApi.getTransactions(accountType, page, pageSize, referenceType),
    enabled: !!accountType,
  });
}

/**
 * Hook to fetch system account contribution records (算力来源明细)
 */
export function useSystemAccountContributionRecords(
  accountType: string,
  regionCode: string | null,
  page: number = 1,
  pageSize: number = 20
) {
  return useQuery({
    queryKey: ['system-accounts', accountType, regionCode, 'contributions', page, pageSize],
    queryFn: () => systemAccountsApi.getContributionRecords(accountType, regionCode, page, pageSize),
    enabled: !!accountType,
  });
}

/**
 * Hook to fetch system account contribution stats (算力明细统计)
 */
export function useSystemAccountContributionStats(accountType: string, regionCode: string | null) {
  return useQuery({
    queryKey: ['system-accounts', accountType, regionCode, 'contribution-stats'],
    queryFn: () => systemAccountsApi.getContributionStats(accountType, regionCode),
    enabled: !!accountType,
  });
}
