import axios from 'axios';

const tradingBaseURL = '/api/trading';

const tradingClient = axios.create({
  baseURL: tradingBaseURL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

tradingClient.interceptors.request.use(
  (config) => {
    const token = typeof window !== 'undefined' ? localStorage.getItem('admin_token') : null;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

tradingClient.interceptors.response.use(
  (response) => {
    // Kong 网关会包装一层 { success, data, timestamp }，需要解包
    if (response.data && response.data.data !== undefined) {
      response.data = response.data.data;
    }
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('admin_token');
      if (typeof window !== 'undefined' && !window.location.pathname.includes('/login')) {
        window.location.href = '/login';
      }
    }
    return Promise.reject(error);
  }
);

export type MarketMakerMode = 'idle' | 'taker' | 'maker';

export interface RunningStatus {
  mode: MarketMakerMode;
  takerRunning: boolean;
  makerRunning: boolean;
  modeDescription?: string;
}

export interface MarketMakerConfig {
  id: string;
  name: string;
  accountSequence: string;
  cashBalance: string;
  shareBalance: string;
  frozenCash: string;
  frozenShares: string;
  availableCash: string;
  availableShares: string;
  maxBuyRatio: string;
  minIntervalMs: number;
  maxIntervalMs: number;
  priceStrategy: string;
  discountRate: string;
  isActive: boolean;
  makerEnabled?: boolean;
  bidEnabled?: boolean;
  bidLevels?: number;
  bidSpread?: string;
  bidLevelSpacing?: string;
  bidQuantityPerLevel?: string;
  askEnabled?: boolean;
  askLevels?: number;
  askSpread?: string;
  askLevelSpacing?: string;
  askQuantityPerLevel?: string;
  refreshIntervalMs?: number;
  lastRefreshAt?: string;
  kavaWalletAddress?: string;
  eusdtWalletAddress?: string;
}

export interface MarketMakerOrder {
  id: string;
  orderNo: string;
  side: 'BID' | 'ASK';
  level: number;
  price: string;
  quantity: string;
  remainingQty: string;
  status: string;
  createdAt: string;
}

export interface DepthLevel {
  price: string;
  quantity: string;
  total: string;
}

export interface DepthData {
  bids: DepthLevel[];
  asks: DepthLevel[];
  timestamp: number;
}

export interface LedgerEntry {
  id: string;
  type: string;
  assetType: string;
  amount: string;
  balanceBefore: string;
  balanceAfter: string;
  tradeNo: string | null;
  orderNo: string | null;
  counterpartySeq: string | null;
  price: string | null;
  quantity: string | null;
  memo: string | null;
  createdAt: string;
}

export const marketMakerApi = {
  // 获取做市商配置（包含运行状态）
  getConfig: async (name: string = 'MAIN_MARKET_MAKER'): Promise<{
    success: boolean;
    config: MarketMakerConfig | null;
    runningStatus: RunningStatus;
  }> => {
    const response = await tradingClient.get(`/admin/market-maker/${name}/config`);
    return response.data;
  },

  // 获取运行状态
  getRunningStatus: async (): Promise<{ success: boolean } & RunningStatus> => {
    const response = await tradingClient.get('/admin/market-maker/status');
    return response.data;
  },

  // 初始化做市商
  initialize: async (data: {
    name?: string;
    accountSequence: string;
    initialCash?: string;
    maxBuyRatio?: number;
    minIntervalMs?: number;
    maxIntervalMs?: number;
  }): Promise<{ success: boolean; message: string; config: MarketMakerConfig }> => {
    const response = await tradingClient.post('/admin/market-maker/initialize', data);
    return response.data;
  },

  // 更新做市商配置
  updateConfig: async (name: string, data: {
    maxBuyRatio?: number;
    minIntervalMs?: number;
    maxIntervalMs?: number;
    priceStrategy?: string;
    discountRate?: number;
    kavaWalletAddress?: string;
    eusdtWalletAddress?: string;
  }): Promise<{ success: boolean; message: string }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/config`, data);
    return response.data;
  },

  // 充值资金
  deposit: async (name: string, amount: string, memo?: string): Promise<{ success: boolean; message: string; newBalance: string }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/deposit`, { amount, memo });
    return response.data;
  },

  // 提现资金
  withdraw: async (name: string, amount: string, memo?: string): Promise<{ success: boolean; message: string; newBalance: string }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/withdraw`, { amount, memo });
    return response.data;
  },

  // 充值积分股
  depositShares: async (name: string, amount: string, memo?: string): Promise<{ success: boolean; message: string; newShareBalance: string }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/deposit-shares`, { amount, memo });
    return response.data;
  },

  // 提取积分股
  withdrawShares: async (name: string, amount: string, memo?: string): Promise<{ success: boolean; message: string; newShareBalance: string }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/withdraw-shares`, { amount, memo });
    return response.data;
  },

  // 区块链提现积分值（fUSDT）
  blockchainWithdrawCash: async (name: string, toAddress: string, amount: string): Promise<{
    success: boolean;
    message: string;
    txHash?: string;
    blockNumber?: number;
    newBalance?: string;
    error?: string;
  }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/blockchain-withdraw-cash`, { toAddress, amount });
    return response.data;
  },

  // 区块链提现积分股（eUSDT）
  blockchainWithdrawShares: async (name: string, toAddress: string, amount: string): Promise<{
    success: boolean;
    message: string;
    txHash?: string;
    blockNumber?: number;
    newBalance?: string;
    error?: string;
  }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/blockchain-withdraw-shares`, { toAddress, amount });
    return response.data;
  },

  // 启动吃单模式
  start: async (name: string): Promise<{ success: boolean; message: string }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/start`);
    return response.data;
  },

  // 停止吃单模式
  stop: async (name: string): Promise<{ success: boolean; message: string }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/stop`);
    return response.data;
  },

  // 手动执行一次吃单
  takeOrder: async (name: string): Promise<{
    success: boolean;
    message: string;
    tradeInfo?: {
      orderNo: string;
      sellOrderNo: string;
      price: string;
      quantity: string;
      amount: string;
    };
  }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/take-order`);
    return response.data;
  },

  // 启动挂单模式
  startMaker: async (name: string): Promise<{ success: boolean; message: string }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/start-maker`);
    return response.data;
  },

  // 停止挂单模式
  stopMaker: async (name: string): Promise<{ success: boolean; message: string }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/stop-maker`);
    return response.data;
  },

  // 刷新挂单
  refreshOrders: async (name: string): Promise<{
    success: boolean;
    message: string;
    bidOrders?: number;
    askOrders?: number;
  }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/refresh-orders`);
    return response.data;
  },

  // 取消所有挂单
  cancelAllOrders: async (name: string): Promise<{ success: boolean; message: string; cancelledCount: number }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/cancel-all-orders`);
    return response.data;
  },

  // 更新挂单配置
  updateMakerConfig: async (name: string, data: {
    bidEnabled?: boolean;
    bidLevels?: number;
    bidSpread?: number;
    bidLevelSpacing?: number;
    bidQuantityPerLevel?: string;
    askEnabled?: boolean;
    askLevels?: number;
    askSpread?: number;
    askLevelSpacing?: number;
    askQuantityPerLevel?: string;
    refreshIntervalMs?: number;
  }): Promise<{ success: boolean; message: string }> => {
    const response = await tradingClient.post(`/admin/market-maker/${name}/maker-config`, data);
    return response.data;
  },

  // 获取做市商挂单列表
  getMakerOrders: async (name: string, params?: {
    side?: 'BID' | 'ASK';
    status?: 'ACTIVE' | 'FILLED' | 'CANCELLED';
    page?: number;
    pageSize?: number;
  }): Promise<{ success: boolean; data: MarketMakerOrder[]; total: number }> => {
    const searchParams = new URLSearchParams();
    if (params?.side) searchParams.append('side', params.side);
    if (params?.status) searchParams.append('status', params.status);
    if (params?.page) searchParams.append('page', params.page.toString());
    if (params?.pageSize) searchParams.append('pageSize', params.pageSize.toString());
    const response = await tradingClient.get(`/admin/market-maker/${name}/maker-orders?${searchParams.toString()}`);
    return response.data;
  },

  // 获取深度数据
  getDepth: async (levels?: number): Promise<{ success: boolean } & DepthData> => {
    const params = levels ? `?levels=${levels}` : '';
    const response = await tradingClient.get(`/admin/market-maker/depth${params}`);
    return response.data;
  },

  // 获取统计信息
  getStats: async (name: string): Promise<{
    success: boolean;
    config: Partial<MarketMakerConfig>;
    recentTrades: any[];
    dailyStats: any[];
  }> => {
    const response = await tradingClient.get(`/admin/market-maker/${name}/stats`);
    return response.data;
  },

  // 获取深度功能开关状态
  getDepthEnabled: async (): Promise<{ enabled: boolean }> => {
    const response = await tradingClient.get('/admin/trading/depth-enabled');
    return response.data;
  },

  // 设置深度功能开关
  setDepthEnabled: async (enabled: boolean): Promise<{ success: boolean; enabled: boolean; message: string }> => {
    const response = await tradingClient.post('/admin/trading/depth-enabled', { enabled });
    return response.data;
  },

  // 获取做市商分类账流水
  getLedgers: async (
    name: string,
    params?: {
      type?: string;
      assetType?: string;
      page?: number;
      pageSize?: number;
    },
  ): Promise<{ success: boolean; data: LedgerEntry[]; total: number }> => {
    const searchParams = new URLSearchParams();
    if (params?.type) searchParams.append('type', params.type);
    if (params?.assetType) searchParams.append('assetType', params.assetType);
    if (params?.page) searchParams.append('page', params.page.toString());
    if (params?.pageSize) searchParams.append('pageSize', params.pageSize.toString());
    const response = await tradingClient.get(`/admin/market-maker/${name}/ledgers?${searchParams.toString()}`);
    return response.data;
  },
};
