import apiClient from "@/lib/axiosClient";
import { API_ENDPOINTS } from "@/lib/apiEndpoints";
import Cookies from "js-cookie";
import { formatRelativeDate } from "@/utils/format";

export interface CoinPackage {
  id: number;
  name: string;
  image: string;
  price: number;
  coin: number;
  webProductPackage: string;
}

export interface WalletBalance {
  walletBalance: number;
  walletAmount: number;
  walletEarning: number;
  channelName: string;
  profileImage: string;
  paypalEmail: string;
  paypalName: string;
}

export interface CoinPurchaseTransaction {
  id: number;
  price: number;
  coin: number;
  description: string;
  status: number;
  createdAt: string;
}

export interface WithdrawalTransaction {
  id: number;
  amount: number;
  paymentType: string;
  paymentDetail: string;
  status: number;
  createdAt: string;
}

export interface GiftTransaction {
  id: number;
  price: number;
  giftName: string;
  channelName: string;
  contentName: string;
  status: number;
  createdAt: string;
}

export interface PaginatedResult<T> {
  items: T[];
  totalRows: number;
  totalPage: number;
  currentPage: number;
  hasMore: boolean;
}

export const walletService = {
  getCoinPackages: async (): Promise<CoinPackage[]> => {
    const res = await apiClient.post(API_ENDPOINTS.GET_COIN_PACKAGE);
    return (res.data.result ?? []).map((r: {
      id: number; name: string; image: string; price: number;
      coin: number; web_product_package: string;
    }) => ({
      id: r.id,
      name: r.name,
      image: r.image,
      price: r.price,
      coin: r.coin,
      webProductPackage: r.web_product_package,
    }));
  },

  getBalance: async (): Promise<WalletBalance> => {
    const userId = Cookies.get("user_id");
    const res = await apiClient.post(API_ENDPOINTS.AUTH.PROFILE, { to_user_id: userId });
    const profile = res.data.result?.[0];
    return {
      walletBalance: profile?.wallet_balance ?? 0,
      walletAmount: parseFloat(profile?.wallet_amount ?? "0") || 0,
      walletEarning: profile?.wallet_earning ?? 0,
      channelName: profile?.channel_name ?? "",
      profileImage: profile?.image ?? "",
      paypalEmail: profile?.paypal_email ?? "",
      paypalName: profile?.paypal_name ?? "",
    };
  },

  getCoinTransactions: async (page = 1): Promise<PaginatedResult<CoinPurchaseTransaction>> => {
    const res = await apiClient.post(API_ENDPOINTS.PAYMENT.GET_COIN_TRANSACTIONS, { page_no: page });
    const data = res.data;
    return {
      items: (data.result ?? []).map((r: {
        id: number; price: number; coin: number; description: string;
        status: number; created_at: string;
      }) => ({
        id: r.id,
        price: r.price,
        coin: r.coin,
        description: r.description,
        status: r.status,
        createdAt: formatRelativeDate(r.created_at),
      })),
      totalRows: data.total_rows ?? 0,
      totalPage: data.total_page ?? 1,
      currentPage: data.current_page ?? 1,
      hasMore: data.more_page ?? false,
    };
  },

  getWithdrawalTransactions: async (page = 1): Promise<PaginatedResult<WithdrawalTransaction>> => {
    const res = await apiClient.post(API_ENDPOINTS.WALLET.GET_WITHDRAWAL_LIST, { page_no: page });
    const data = res.data;
    return {
      items: (data.result ?? []).map((r: {
        id: number; amount: number; payment_type: string;
        payment_detail: string; status: number; created_at: string;
      }) => ({
        id: r.id,
        amount: r.amount,
        paymentType: r.payment_type,
        paymentDetail: r.payment_detail,
        status: r.status,
        createdAt: formatRelativeDate(r.created_at),
      })),
      totalRows: data.total_rows ?? 0,
      totalPage: data.total_page ?? 1,
      currentPage: data.current_page ?? 1,
      hasMore: data.more_page ?? false,
    };
  },

  getGiftTransactions: async (page = 1): Promise<PaginatedResult<GiftTransaction>> => {
    const res = await apiClient.post(API_ENDPOINTS.WALLET.GET_GIFT_TRANSACTIONS, { page_no: page });
    const data = res.data;
    return {
      items: (data.result ?? []).map((r: {
        id: number; price: number; gift_name: string;
        channel_name: string; content_name: string; status: number; created_at: string;
      }) => ({
        id: r.id,
        price: r.price,
        giftName: r.gift_name,
        channelName: r.channel_name,
        contentName: r.content_name,
        status: r.status,
        createdAt: formatRelativeDate(r.created_at),
      })),
      totalRows: data.total_rows ?? 0,
      totalPage: data.total_page ?? 1,
      currentPage: data.current_page ?? 1,
      hasMore: data.more_page ?? false,
    };
  },

  submitWithdrawal: async (amount: string, paypalEmail: string, paypalName: string): Promise<void> => {
    await apiClient.post(API_ENDPOINTS.WALLET.ADD_WITHDRAWAL, {
      amount,
      payment_type: "paypal",
      payment_detail: `email: ${paypalEmail}, name: ${paypalName}`,
    });
  },
};
