import apiClient from '../../../shared/services/apiClient';
import type { Booking } from '../../bookings/services/bookingService';

export interface PaymentData {
  booking_id: number;
  amount: number;
  payment_method: 'cash' | 'bank_transfer' | 'stripe' | 'paypal' | 'borica';
  transaction_id?: string;
  notes?: string;
}

export interface Payment {
  id: number;
  booking_id: number;
  amount: number;
  payment_method: 'cash' | 'bank_transfer' | 'credit_card' | 'debit_card' | 'e_wallet' | 'stripe' | 'paypal' | 'borica';
  payment_type: 'full' | 'deposit' | 'remaining';
  deposit_percentage?: number;
  payment_status: 'pending' | 'completed' | 'failed' | 'refunded';
  transaction_id?: string;
  payment_date?: string;
  notes?: string;
  createdAt: string;
  updatedAt: string;
  booking?: {
    id: number;
    booking_number: string;
    user?: {
      name: string;
      email?: string;
    };
  };
}

export interface BankInfo {
  bank_name: string;
  bank_code: string;
  account_number: string;
  account_name: string;
  amount: number;
  content: string;
  qr_url: string;
}

export interface PaymentResponse {
  success: boolean;
  data: {
    payment: Payment;
  };
  message?: string;
}

export const createPayment = async (
  paymentData: PaymentData
): Promise<PaymentResponse> => {
  const response = await apiClient.post<{ status?: string; success?: boolean; data?: unknown; message?: string }>(
    '/payments',
    paymentData
  );
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    data: data.data || {},
    message: data.message,
  };
};

export const getPaymentByBookingId = async (
  bookingId: number
): Promise<PaymentResponse> => {
  const response = await apiClient.get<{ status?: string; success?: boolean; data?: unknown; message?: string }>(
    `/payments/${bookingId}`
  );
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    data: data.data || {},
    message: data.message,
  };
};

export const confirmBankTransfer = async (
  bookingId: number,
  transactionId?: string,
  receipt?: File
): Promise<{ success: boolean; message?: string }> => {
  const formData = new FormData();
  formData.append('booking_id', bookingId.toString());
  
  if (transactionId) {
    formData.append('transaction_id', transactionId);
  }
  
  if (receipt) {
    formData.append('receipt', receipt);
  }

  
  const response = await apiClient.post(
    '/payments/confirm',
    formData
  );
  
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    message: data.message,
  };
};

export const getBankTransferInfo = async (
  paymentId: number
): Promise<{ 
  success: boolean; 
  data: { payment: Payment; bank_info: BankInfo }; 
  message?: string;
}> => {
  const response = await apiClient.get(
    `/payments/${paymentId}/bank-info`
  );
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    data: data.data || {},
    message: data.message,
  };
};

export const confirmDepositPayment = async (
  paymentId: number,
  transactionId?: string
): Promise<{
  success: boolean;
  data: { payment: Payment; booking: Booking };
  message?: string;
}> => {
  const response = await apiClient.post(
    '/payments/confirm-deposit',
    {
      payment_id: paymentId,
      transaction_id: transactionId,
    }
  );
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    data: data.data || {},
    message: data.message,
  };
};

export const notifyPaymentCompletion = async (
  paymentId: number,
  notes?: string
): Promise<{ success: boolean; message?: string }> => {
  const response = await apiClient.post(
    '/payments/notify',
    {
      payment_id: paymentId,
      notes,
    }
  );
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    message: data.message,
  };
};

export const getPayments = async (params?: {
  booking_id?: number;
  status?: string;
  page?: number;
  limit?: number;
}): Promise<{
  success: boolean;
  data: {
    payments: Payment[];
    pagination?: {
      total: number;
      page: number;
      limit: number;
      totalPages: number;
    };
  };
  message?: string;
}> => {
  const response = await apiClient.get('/payments', { params });
  
  const data = response.data;
  return {
    success: data.status === "success" || data.success === true,
    data: data.data || { payments: [] },
    message: data.message,
  };
};

export const getPaymentsByBookingId = async (
  bookingId: number
): Promise<{
  success: boolean;
  data: { payments: Payment[] };
  message?: string;
}> => {
  const response = await apiClient.get(
    `/payments/booking/${bookingId}`
  );
  
  const data = response.data;
  return {
    success: data.status === "success" || data.success === true,
    data: data.data || { payments: [] },
    message: data.message,
  };
};

export const createStripePaymentIntent = async (
  bookingId: number,
  amount: number,
  currency: string = 'usd'
): Promise<{
  success: boolean;
  data: {
    client_secret: string;
    payment_intent_id: string;
    publishable_key: string;
  };
  message?: string;
}> => {
  const response = await apiClient.post(
    '/payments/stripe/create-intent',
    {
      booking_id: bookingId,
      amount,
      currency,
    }
  );
  
  const data = response.data;
  return {
    success: data.status === "success" || data.success === true,
    data: data.data || {},
    message: data.message,
  };
};

export const confirmStripePayment = async (
  paymentIntentId: string,
  bookingId: number
): Promise<{
  success: boolean;
  data: {
    payment: Payment;
    booking: {
      id: number;
      booking_number: string;
      status: string;
    };
  };
  message?: string;
}> => {
  const response = await apiClient.post(
    '/payments/stripe/confirm',
    {
      payment_intent_id: paymentIntentId,
      booking_id: bookingId,
    }
  );
  
  const data = response.data;
  return {
    success: data.status === "success" || data.success === true,
    data: data.data || {},
    message: data.message,
  };
};

export const createPayPalOrder = async (
  bookingId: number,
  amount: number,
  currency: string = 'USD',
  returnUrl?: string,
  cancelUrl?: string
): Promise<{
  success: boolean;
  data: {
    order_id: string;
    approval_url: string;
    status: string;
  };
  message?: string;
}> => {
  const response = await apiClient.post(
    '/payments/paypal/create-order',
    {
      booking_id: bookingId,
      amount,
      currency,
      return_url: returnUrl,
      cancel_url: cancelUrl,
    }
  );
  
  const data = response.data;
  return {
    success: data.status === "success" || data.success === true,
    data: data.data || {},
    message: data.message,
  };
};

export const capturePayPalPayment = async (
  orderId: string,
  bookingId: number
): Promise<{
  success: boolean;
  data: {
    payment: Payment;
    booking: {
      id: number;
      booking_number: string;
      status: string;
    };
  };
  message?: string;
}> => {
  const response = await apiClient.post(
    '/payments/paypal/capture',
    {
      order_id: orderId,
      booking_id: bookingId,
    }
  );
  
  const data = response.data;
  return {
    success: data.status === "success" || data.success === true,
    data: data.data || {},
    message: data.message,
  };
};

export const cancelPayPalPayment = async (
  bookingId: number
): Promise<{
  success: boolean;
  message?: string;
}> => {
  const response = await apiClient.post(
    '/payments/paypal/cancel',
    {
      booking_id: bookingId,
    }
  );
  
  const data = response.data;
  return {
    success: data.status === "success" || data.success === true,
    message: data.message,
  };
};

export const createBoricaPayment = async (
  bookingId: number,
  amount: number,
  currency: string = 'BGN',
  returnUrl?: string
): Promise<{
  success: boolean;
  data: {
    payment_request: {
      terminal_id: string;
      merchant_id: string;
      order_id: string;
      amount: string;
      currency: string;
      description: string;
      timestamp: string;
      signature: string;
      gateway_url: string;
      return_url: string;
      trtype: string;
    };
    payment_id: number;
    transaction_id: string;
  };
  message?: string;
}> => {
  const response = await apiClient.post(
    '/payments/borica/create-payment',
    {
      booking_id: bookingId,
      amount,
      currency,
      return_url: returnUrl,
    }
  );
  
  const data = response.data;
  return {
    success: data.status === "success" || data.success === true,
    data: data.data || {},
    message: data.message,
  };
};

export const confirmBoricaPayment = async (
  responseData: Record<string, string>
): Promise<{
  success: boolean;
  data: {
    payment: Payment;
    booking: {
      id: number;
      booking_number: string;
      status: string;
    };
  };
  message?: string;
}> => {
  const response = await apiClient.post(
    '/payments/borica/confirm',
    responseData
  );
  
  const data = response.data;
  return {
    success: data.status === "success" || data.success === true,
    data: data.data || {},
    message: data.message,
  };
};

export default {
  createPayment,
  getPayments,
  getPaymentByBookingId,
  confirmBankTransfer,
  getBankTransferInfo,
  confirmDepositPayment,
  notifyPaymentCompletion,
  getPaymentsByBookingId,
  createStripePaymentIntent,
  confirmStripePayment,
  createPayPalOrder,
  capturePayPalPayment,
  cancelPayPalPayment,
  createBoricaPayment,
  confirmBoricaPayment,
};
