import { apiClient } from '@/lib/api/client';
import type {
  UserOverview,
  UserDetail,
  ContributionRecord,
  MiningRecord,
  TradeOrder,
  ReferralTreeData,
  PlantingLedgerResponse,
  WalletLedgerResponse,
} from '@/types/user';
import type { PaginatedResponse, PaginationParams } from '@/types/api';

// 转换后端用户数据到前端 UserOverview 格式
function transformUserOverview(backendUser: any): UserOverview {
  return {
    accountSequence: backendUser.accountSequence,
    nickname: backendUser.realName || backendUser.nickname || '',
    phone: backendUser.phone || '',
    phoneNumberMasked: backendUser.phone,
    avatar: null,
    hasAdopted: backendUser.contribution?.hasAdopted || false,
    totalContribution: backendUser.contribution?.totalContribution || '0',
    effectiveContribution: backendUser.contribution?.effectiveContribution || '0',
    miningBalance: backendUser.mining?.availableBalance || '0',
    tradingBalance: backendUser.trading?.shareBalance || '0',
    frozenBalance: '0',
    // 认种数据 - 从后端 adoption 字段获取
    personalAdoptions: backendUser.adoption?.personalAdoptionCount || 0,
    personalAdoptionOrders: backendUser.adoption?.personalAdoptionOrders || 0,
    teamAdoptions: backendUser.adoption?.teamAdoptions || 0,
    teamAdoptionOrders: backendUser.adoption?.teamAdoptionOrders || 0,
    // 推荐人
    referrerId: backendUser.referral?.referrerAccountSequence || null,
    status: backendUser.status?.toLowerCase() as 'active' | 'frozen' | 'deactivated',
    isOnline: false,
    createdAt: backendUser.createdAt,
  };
}

// 转换后端用户详情到前端 UserDetail 格式
function transformUserDetail(backendUser: any): UserDetail {
  return {
    ...transformUserOverview(backendUser),
    // 推荐关系
    referrerAccountSequence: backendUser.referral?.referrerAccountSequence || null,
    referrerNickname: backendUser.referral?.referrerNickname || null,
    referrerId: backendUser.referral?.referrerAccountSequence || null,
    // 直推数据
    directReferralCount: backendUser.team?.directReferralCount || backendUser.contribution?.directReferralCount || 0,
    directReferralAdoptedCount: backendUser.adoption?.directReferralAdoptions || 0,
    // 团队数据
    teamSize: backendUser.team?.teamMemberCount || 0,
    teamAdoptedCount: backendUser.adoption?.teamAdoptions || 0,
    teamAddresses: backendUser.team?.teamMemberCount || 0,
    // 认种数据
    personalAdoptions: backendUser.adoption?.personalAdoptionCount || 0,
    teamAdoptions: backendUser.adoption?.teamAdoptions || 0,
    // 算力明细及解锁状态
    contributions: {
      personal: backendUser.contribution?.personalContribution || '0',
      teamLevel: backendUser.contribution?.teamLevelContribution || '0',
      teamBonus: backendUser.contribution?.teamBonusContribution || '0',
      total: backendUser.contribution?.totalContribution || '0',
      // 解锁状态
      hasAdopted: backendUser.contribution?.hasAdopted || false,
      directReferralCount: backendUser.contribution?.directReferralCount || 0,
      unlockedLevelDepth: backendUser.contribution?.unlockedLevelDepth || 0,
      unlockedBonusTiers: backendUser.contribution?.unlockedBonusTiers || 0,
    },
    kycStatus: backendUser.kycStatus,
    registeredAt: backendUser.createdAt,
  };
}

export const usersApi = {
  getList: async (params: PaginationParams & { keyword?: string }): Promise<PaginatedResponse<UserOverview>> => {
    // 转换参数名: keyword -> search
    const apiParams = {
      page: params.page,
      pageSize: params.pageSize,
      search: params.keyword,
    };
    const response = await apiClient.get('/users', { params: apiParams });
    // 后端返回格式: { data: [...], pagination: { page, pageSize, total, totalPages } }
    // 前端期望格式: { items: [...], total, page, pageSize, totalPages }
    const result = response.data.data;
    return {
      items: (result.data || []).map((user: any) => transformUserOverview(user)),
      total: result.pagination?.total || 0,
      page: result.pagination?.page || 1,
      pageSize: result.pagination?.pageSize || 20,
      totalPages: result.pagination?.totalPages || 0,
    };
  },

  getDetail: async (accountSequence: string): Promise<UserDetail> => {
    const response = await apiClient.get(`/users/${accountSequence}`);
    return transformUserDetail(response.data.data);
  },

  getContributionRecords: async (
    accountSequence: string,
    params: PaginationParams & { sortBy?: string; sortOrder?: 'asc' | 'desc' }
  ): Promise<PaginatedResponse<ContributionRecord>> => {
    const response = await apiClient.get(`/users/${accountSequence}/contributions`, { params });
    const result = response.data.data;
    // 后端返回 records/pagination，前端期望 items/total/totalPages
    return {
      items: result.records || [],
      total: result.pagination?.total || 0,
      page: result.pagination?.page || 1,
      pageSize: result.pagination?.pageSize || 20,
      totalPages: result.pagination?.totalPages || 0,
    };
  },

  getMiningRecords: async (
    accountSequence: string,
    params: PaginationParams
  ): Promise<PaginatedResponse<MiningRecord>> => {
    const response = await apiClient.get(`/users/${accountSequence}/mining-records`, { params });
    const result = response.data.data;
    return {
      items: result.records || [],
      total: result.pagination?.total || 0,
      page: result.pagination?.page || 1,
      pageSize: result.pagination?.pageSize || 20,
      totalPages: result.pagination?.totalPages || 0,
    };
  },

  getTradeOrders: async (
    accountSequence: string,
    params: PaginationParams
  ): Promise<PaginatedResponse<TradeOrder>> => {
    const response = await apiClient.get(`/users/${accountSequence}/orders`, { params });
    const result = response.data.data;
    return {
      items: result.orders || [],
      total: result.pagination?.total || 0,
      page: result.pagination?.page || 1,
      pageSize: result.pagination?.pageSize || 20,
      totalPages: result.pagination?.totalPages || 0,
    };
  },

  // 从 admin-web 复用的 API
  getReferralTree: async (
    accountSequence: string,
    direction: 'up' | 'down' | 'both' = 'both',
    depth: number = 1
  ): Promise<ReferralTreeData> => {
    const response = await apiClient.get(`/users/${accountSequence}/referral-tree`, {
      params: { direction, depth },
    });
    return response.data.data;
  },

  getPlantingLedger: async (
    accountSequence: string,
    params: PaginationParams
  ): Promise<PlantingLedgerResponse> => {
    const response = await apiClient.get(`/users/${accountSequence}/planting-ledger`, { params });
    return response.data.data;
  },

  getWalletLedger: async (
    accountSequence: string,
    params: PaginationParams
  ): Promise<WalletLedgerResponse> => {
    const response = await apiClient.get(`/users/${accountSequence}/wallet-ledger`, { params });
    return response.data.data;
  },

  getBatchMiningRecords: async (
    accountSequence: string,
    params: PaginationParams
  ): Promise<{
    records: BatchMiningRecord[];
    total: number;
    page: number;
    pageSize: number;
    totalPages: number;
    totalAmount: string;
  }> => {
    const response = await apiClient.get(`/users/${accountSequence}/batch-mining-records`, { params });
    return response.data.data;
  },

  getP2pTransfers: async (
    params: PaginationParams & { search?: string }
  ): Promise<{
    items: P2pTransferRecord[];
    total: number;
    totalPages: number;
    page: number;
    pageSize: number;
    summary: { totalFee: string; totalAmount: string; totalCount: number };
  }> => {
    const response = await apiClient.get('/users/p2p-transfers', { params });
    const result = response.data.data;
    return {
      items: result.data || [],
      total: result.pagination?.total || 0,
      page: result.pagination?.page || 1,
      pageSize: result.pagination?.pageSize || 20,
      totalPages: result.pagination?.totalPages || 0,
      summary: result.summary || { totalFee: '0', totalAmount: '0', totalCount: 0 },
    };
  },

  // ========== Capability 权限管理 API ==========

  getCapabilities: async (accountSequence: string): Promise<CapabilityItem[]> => {
    const response = await apiClient.get(`/capabilities/users/${accountSequence}`);
    const data = response.data.data;
    return Array.isArray(data) ? data : [];
  },

  setCapability: async (
    accountSequence: string,
    dto: { capability: string; enabled: boolean; reason?: string; expiresAt?: string },
  ): Promise<CapabilityItem[]> => {
    const response = await apiClient.put(`/capabilities/users/${accountSequence}`, dto);
    const data = response.data.data;
    return Array.isArray(data) ? data : [];
  },

  setCapabilities: async (
    accountSequence: string,
    capabilities: { capability: string; enabled: boolean; reason?: string; expiresAt?: string }[],
  ): Promise<CapabilityItem[]> => {
    const response = await apiClient.put(`/capabilities/users/${accountSequence}/bulk`, { capabilities });
    const data = response.data.data;
    return Array.isArray(data) ? data : [];
  },

  getCapabilityLogs: async (
    accountSequence: string,
    params: PaginationParams,
  ): Promise<{ data: CapabilityLogItem[]; total: number; page: number; pageSize: number }> => {
    const response = await apiClient.get(`/capabilities/users/${accountSequence}/logs`, { params });
    const result = response.data.data;
    return {
      data: result.data || [],
      total: result.total || 0,
      page: result.page || 1,
      pageSize: result.pageSize || 20,
    };
  },

  // ========== 预种卖出限制 API ==========

  getPrePlantingRestriction: async (accountSequence: string): Promise<{ isRestricted: boolean }> => {
    const response = await apiClient.get(`/pre-planting-restriction/${accountSequence}`);
    const data = response.data.data;
    return { isRestricted: data?.isRestricted ?? false };
  },

  unlockPrePlantingRestriction: async (accountSequence: string, reason?: string): Promise<void> => {
    await apiClient.post(`/pre-planting-restriction/${accountSequence}/unlock`, { reason });
  },
};

// Capability 类型
export interface CapabilityItem {
  capability: string;
  enabled: boolean;
  reason?: string;
  disabledBy?: string;
  disabledAt?: string;
  expiresAt?: string;
}

export interface CapabilityLogItem {
  id: string;
  accountSequence: string;
  capability: string;
  action: string;
  reason?: string;
  operatorId?: string;
  previousValue: boolean;
  newValue: boolean;
  expiresAt?: string;
  createdAt: string;
}

// P2P转账记录类型
export interface P2pTransferRecord {
  transferNo: string;
  fromAccountSequence: string;
  fromPhone?: string | null;
  fromNickname?: string | null;
  toAccountSequence: string;
  toPhone: string;
  toNickname?: string | null;
  amount: string;
  fee?: string;
  memo?: string | null;
  status: string;
  createdAt: string;
}

// 批量补发记录类型
export interface BatchMiningRecord {
  id: string;
  accountSequence: string;
  batch: number;
  phase: number;
  treeCount: number;
  daysInPhase: number;
  preMineDays: number;
  userContribution: string;
  networkContribution: string;
  contributionRatio: string;
  totalSeconds: string;
  amount: string;
  remark: string | null;
  createdAt: string;
}
