import { apiClient } from '@/lib/api/client';
import type {
  SystemAccount,
  SystemAccountsResponse,
  SystemAccountsSummary,
} from '@/types/system-account';

export interface SystemMiningRecord {
  id: string;
  accountType: string;
  miningMinute: string;
  contributionRatio: string;
  totalContribution: string;
  secondDistribution: string;
  minedAmount: string;
  createdAt: string;
}

export interface SystemMiningRecordsResponse {
  records: SystemMiningRecord[];
  total: number;
  page: number;
  pageSize: number;
}

export interface SystemTransaction {
  id: string;
  accountType: string;
  type: string;
  amount: string;
  balanceBefore: string;
  balanceAfter: string;
  referenceId?: string;
  referenceType?: string;
  memo?: string;
  createdAt: string;
}

export interface SystemTransactionsResponse {
  transactions: SystemTransaction[];
  total: number;
  page: number;
  pageSize: number;
}

// 来源类型枚举
export type ContributionSourceType =
  | 'FIXED_RATE'        // 固定比例分配（OPERATION 12%、PROVINCE 1%、CITY 2%）
  | 'LEVEL_OVERFLOW'    // 层级溢出归总部（上线未解锁该级别）
  | 'LEVEL_NO_ANCESTOR' // 无上线归总部（该级无上线）
  | 'BONUS_TIER_1'      // 团队奖励T1未解锁归总部
  | 'BONUS_TIER_2'      // 团队奖励T2未解锁归总部
  | 'BONUS_TIER_3';     // 团队奖励T3未解锁归总部

// 算力来源明细记录
export interface SystemContributionRecord {
  originalRecordId: string;
  accountType: string;
  regionCode: string | null;
  sourceAdoptionId: string;
  sourceAccountSequence: string;
  // 来源类型
  sourceType: ContributionSourceType;
  levelDepth: number | null;  // 层级深度（1-15），仅对 LEVEL_OVERFLOW 和 LEVEL_NO_ANCESTOR 有效
  // 认种订单详情
  adoptionTreeCount: number;
  adoptionDate: string | null;
  adoptionStatus: string | null;
  contributionPerTree: string;
  // 用户信息
  sourceUserPhone: string | null;
  sourceUserName: string | null;
  // 分配信息
  distributionRate: string;
  amount: string;
  effectiveDate: string;
  expireDate: string | null;
  isExpired: boolean;
  createdAt: string;
  syncedAt: string;
}

export interface SystemContributionRecordsResponse {
  records: SystemContributionRecord[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 算力明细统计
export interface SystemContributionStats {
  accountType: string;
  name: string;
  baseType: string;
  regionCode: string | null;
  totalContribution: string;
  recordCount: number;
  sumFromRecords: string;
  uniqueAdoptionCount: number;
  uniqueUserCount: number;
}

export const systemAccountsApi = {
  /**
   * Get all system accounts (merged local + synced data)
   */
  getList: async (): Promise<SystemAccountsResponse> => {
    const response = await apiClient.get('/system-accounts');
    return response.data.data;
  },

  /**
   * Get system accounts summary with mining config and circulation pool
   */
  getSummary: async (): Promise<SystemAccountsSummary> => {
    const response = await apiClient.get('/system-accounts/summary');
    return response.data.data;
  },

  /**
   * Get system account mining records
   */
  getMiningRecords: async (
    accountType: string,
    page: number = 1,
    pageSize: number = 20
  ): Promise<SystemMiningRecordsResponse> => {
    const response = await apiClient.get(
      `/system-accounts/${accountType}/records`,
      { params: { page, pageSize } }
    );
    return response.data.data;
  },

  /**
   * Get system account transactions
   */
  getTransactions: async (
    accountType: string,
    page: number = 1,
    pageSize: number = 20,
    referenceType?: string | null,
  ): Promise<SystemTransactionsResponse> => {
    const params: Record<string, any> = { page, pageSize };
    if (referenceType) {
      params.referenceType = referenceType;
    }
    const response = await apiClient.get(
      `/system-accounts/${accountType}/transactions`,
      { params }
    );
    return response.data.data;
  },

  /**
   * Get system account contribution records (算力来源明细)
   * 显示该账户的每笔算力来自哪个认种订单
   */
  getContributionRecords: async (
    accountType: string,
    regionCode: string | null,
    page: number = 1,
    pageSize: number = 20
  ): Promise<SystemContributionRecordsResponse> => {
    const params: Record<string, any> = { page, pageSize };
    if (regionCode) {
      params.regionCode = regionCode;
    }
    const response = await apiClient.get(
      `/system-accounts/${accountType}/contributions`,
      { params }
    );
    return response.data.data;
  },

  /**
   * Get system account contribution stats (算力明细统计)
   */
  getContributionStats: async (
    accountType: string,
    regionCode: string | null
  ): Promise<SystemContributionStats> => {
    const params: Record<string, any> = {};
    if (regionCode) {
      params.regionCode = regionCode;
    }
    const response = await apiClient.get(
      `/system-accounts/${accountType}/contribution-stats`,
      { params }
    );
    return response.data.data;
  },
};

// Helper to categorize accounts for display
export function categorizeAccounts(accounts: SystemAccount[]) {
  // 核心系统账户类型（HQ、运营、手续费）
  const coreAccounts = ['HEADQUARTERS', 'OPERATION', 'FEE'];
  // 区域账户类型（省、市）
  const regionAccounts = ['PROVINCE', 'CITY'];

  return {
    mainPools: [] as SystemAccount[], // 池账户现在从 poolAccounts API 获取
    systemAccounts: accounts.filter((a) => coreAccounts.includes(a.accountType)),
    fixedAccounts: accounts.filter((a) => regionAccounts.includes(a.accountType)),
    otherAccounts: accounts.filter(
      (a) =>
        !coreAccounts.includes(a.accountType) &&
        !regionAccounts.includes(a.accountType)
    ),
  };
}
