package com.dspread.pos.ui.pinpad;

import android.app.Application;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import com.dspread.pos.common.base.BaseAppViewModel;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import org.json.JSONException;
import org.json.JSONObject;

public class PinpadViewModel extends BaseAppViewModel {
    private static final String TAG = "PinpadVM";

    public ObservableField<String> currencyCode = new ObservableField<>("RUB");
    public ObservableField<String> amount = new ObservableField<>("10.00");
    public ObservableField<String> countdown = new ObservableField<>("10");

    // Add this SingleLiveEvent for signal-based navigation
    public SingleLiveEvent<String> paymentStartEvent = new SingleLiveEvent<>();

    public PinpadViewModel(@NonNull Application application) {
        super(application);
    }

    public void setInitialAmount(String initialAmount) {
        if (initialAmount != null && !initialAmount.isEmpty()) {
            amount.set(formatAmount(initialAmount));
        }
    }

    public void updateCountdown(long seconds) {
        countdown.set(String.valueOf(seconds));
    }

    private String formatAmount(String amountStr) {
        try {
            // Convert cents to dollars format
            double amountDouble = Double.parseDouble(amountStr) / 100.0;
            return String.format("%.2f", amountDouble);
        } catch (NumberFormatException e) {
            return "0.00";
        }
    }

    @Override
    protected void onPaymentRedirected(String jsonString) {
        Log.d(TAG, "onPaymentRedirected - processing redirect payment");
        Log.d(TAG, "jsonString" + jsonString);

        try {
            JSONObject results = new JSONObject(jsonString);
            String status = results.optString("status", "");

            switch (status) {
                case "signal":
                    Log.d(TAG, "Signal Redirect Payment received");

                    // Get the amount from the signal (or use the current amount)
                    String signalAmount = results.optString("amount", null);
                    Log.d(TAG, "onPaymentRedirected: amount " + signalAmount);
                    if (signalAmount != null) {
                        amount.set(formatAmount(signalAmount));
                    }

                    // Trigger navigation via the event
//                    String amountToPass = results.optString("rawAmount", getRawAmount());
                    paymentStartEvent.postValue(signalAmount);
                    break;

                default:
                    Log.w(TAG, "Unknown JSON type: " + status);
            }
        } catch (JSONException e) {
            Log.e(TAG, "Error parsing JSON", e);
        }
    }

    // Helper method to get raw amount (without formatting)
    private String getRawAmount() {
        String formatted = amount.get();

        try {
            // Convert formatted amount back to raw cents

            if (formatted != null) {
                double amountDouble = Double.parseDouble(formatted);
                return String.valueOf((int)(amountDouble * 100));
            }
        } catch (NumberFormatException e) {
            Log.e(TAG, "Error converting amount back to raw", e);
        }
        return formatted; // default fallback
    }

    // Method to manually trigger payment (if needed)
//    public void triggerPayment() {
//        paymentStartEvent.postValue(getRawAmount());
//    }
}