import axios from 'axios';
import * as SecureStore from 'expo-secure-store';
import { EXPO_PUBLIC_API_URL } from '@env';

class WalletService {
    private apiUrl: string;

    constructor() {
        this.apiUrl = EXPO_PUBLIC_API_URL;
        if (!this.apiUrl) {
            throw new Error('API URL is not defined in environment variables');
        }
    }

    async getCouponForSpecificUser(userID: string) {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/promotion/coupons/${userID}`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 || response.status === 201) {
                console.log('API Response:', response.data);
                return response.data;
            } else {
                console.log('getCoupon failed:', response.status);
                return false;
            }
        } catch (error) {
            console.error('Error in getCouponForSpecificUser:', error);
            throw error;
        }
    }

    async getCustomerInfo() {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/customer`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 || response.status === 201) {
                const info = response.data;
                return info;
            } else {
                console.error('get customer info failed:', response.status);
                return false;
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error('get customer info error:', error.response?.data?.message || error.message);
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }

    async getWalletBalance() {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/customer/wallet`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200) {
                const walletBalance = response.data.data;
                // console.log(`i am wallet balance`, walletBalance)
                // console.log('getWalletBalance successful!');

                return walletBalance;
            } else {
                console.error('getWalletBalance failed:', response.status);
                return false;
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error('getWallet error:', error.response?.data?.message || error.message);
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }

    async getOutTradeNo() {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/qfpay/out_trade_no`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200) {
                const outTradeNo = response.data.out_trade_no;

                return outTradeNo;
            } else {
                console.error('get outTradeNo failed:', response.status);
                return false;
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error('get outTradeNo error:', error.response?.data?.message || error.message);
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }

    async getTransactionRecord() {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/wallet/transaction/record`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200) {
                const walletBalance = response.data;

                return walletBalance;
            } else {
                console.error('getWalletBalance failed:', response.status);
                return false;
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error('getWallet error:', error.response?.data?.message || error.message);
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }

    async submitPayment(
        stationID: string,
        connector: string,
        user: string,
        book_time: string,
        end_time: string,
        total_power: string,
        total_fee: string,
        promotion_code: string,
        car: string,
        type?: string,
        is_ic_call?: boolean
    ) {
        try {
            const payload = {
                stationID,
                connector,
                user,
                book_time,
                end_time,
                total_power,
                total_fee,
                promotion_code,
                car,
                type,
                is_ic_call
            };
            console.log('Submitting payment with payload:', payload);

            const response = await axios.post(`${this.apiUrl}/clients/pay`, payload, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 || response.status === 201) {
                console.log('submit payment successful:', response.data);
                return response.data;
            } else {
                console.log('submit payment failed:', response.status);
                return false;
            }
        } catch (error) {
            console.log('Error submitting payment:', error);
            return false;
        }
    }

    async selectPaymentType() {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/qfpay/type`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 || response.status === 201) {
                const info = response.data;
                return info;
            } else {
                console.error('get customer info failed:', response.status);
                return false;
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error('get customer info error:', error.response?.data?.message || error.message);
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }

    async submitPaymentAfterSelectingType(amount: number, pay_type: string, return_url?: string) {
        try {
            const response = await axios.get(
                `${this.apiUrl}/clients/qfpay/session?amount=${amount}&pay_type=${pay_type}&return_url=${return_url}`,
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                    }
                }
            );
            // if (response.status === 200 || response.status === 201) {
            if (response) {
                const info = response.data;
                return info;
            } else {
                console.error('get customer info failed:', response.status);
                return false;
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error('get customer info error:', error.response?.data?.message || error.message);
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }
    async checkPaymentStatus(out_trade_no: string) {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/qfpay/check/transaction/${out_trade_no}`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            console.log('checkPaymentStatus API service response,', response.data);
            console.log('is it Array.isArray(response.data.data)?? ', Array.isArray(response.data.data));
            console.log('is it  response.data.data.length > 0???', response.data.data.length > 0);
            if (Array.isArray(response.data.data) && response.data.data.length > 0) {
                // If it's not empty, consider it a success and return the data
                return response.data.data;
            } else {
                // If it's an empty array, consider it false
                return false;
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error('check payment status error:', error.response?.data?.message || error.message);
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }
}
export const walletService = new WalletService();
